Home > database >  Combine two React files into one
Combine two React files into one

Time:06-15

I have two files that return html fragments. They are identical except for the image. The fact is that the server has different paths to the playlist image and the genre image.

props.items.images[0].url

and

props.items.icons[0].url

because of this, I had to distribute this code to two different files. How could I combine them into one?


    const playListClick = e => {
        props.onClick(e.target.title);
    }    

    return (
        <section id={props.selectedValue} className="collum collum__hidden" onClick={playListClick}>
        <a className="link__decoration link__track hover__track link__one" href="#">
          <div>
            {props.items.map((item, idx) => 
            <div className="container" key={idx   1} title={item.id} >
              <div className="content__track" title={item.id}>
                <img className="img__tarck" title={item.id} src={item.images[0].url}/>
                <div className="name" title={item.id}>{item.name}</div>
              </div>
            </div>)}
          </div> 
        </a>
        </section>
    );
}
const Genre = props => {    

const genreClick = e => {
    props.onClick(e.target.title);
}

return (
    <section id={props.selectedValue} className="collum collum__hidden" onClick={genreClick}>
    <a className="link__decoration link__track hover__track link__one" href="#">
      <div>
        {props.items.map((item, idx) => 
        <div className="container" key={idx   1} title={item.id}>
          <div className="content__track" title={item.id}>
            <img className="img__tarck" title={item.id} src={item.icons[0].url}/>
            <div className="name" title={item.id}>{item.name}</div>
          </div>
        </div>)}
      </div> 
    </a>
    </section>
);

CodePudding user response:

You can use a Conditional (ternary) Operator to look if icons exists and if not fallback to using the image. Further assistance is hard due to not knowing the surrounding circumstances.

        <img className="img__tarck" title={item.id} src={item.icons ? item.icons[0].url : item.images[0].url}/>
  • Related