Search code examples
javascriptreactjscomponentsreact-propsconditional-operator

I have a problem using the Ternary Operator in React.js


I have a page that is supposed to generate sections automatically. Everything transfers fine except the ternary operator.

The data I using:

carList = [
    {
        id: 0,
        brand: "Lorem",
        model: "Lorem",
        dealer: "Lorem",
        main_image: "Lorem",
        sections: [
            {
                id: 0,
                section_type: "",
                section_title: "Lorem",
                section_text: "Lorem Lorem Lorem Lorem Lorem",
                image_left: "Lorem1.png",
                image_center: null,
                image_right: null
            }
       ]
  }

IMPORTANT: The data is entered manually, it is not imported from JSON

The problem arises when I want to check the ternary operator if "image_left" or "right" is null.

This is how they are sent:

const { car_id } = this.state;

    const sections = this.carList[car_id].sections.map((section, index) => (
        <CarContent data={this.carList} car_id={this.state.car_id} section_id={this.carList[car_id].sections[index].id} />
    ))

And this is how they are received:

const CarContent = (props) => {
const { car_id, data, section_id } = props;
const section = data[car_id].sections[section_id];

return (
    <div className={section.section_type}>
        <div className="section_images">
            {section.image_left !== null ? <div className="image_left"> // Here < ------
                <img src={section.image_left} alt="" />
            </div> : ""}
            {(section.image_right !== null) ? <div className="image_right"> // And here < ------
                <img src={section.image_right} alt="" />
            </div> : ""}
        </div>
    </div>
  );
}

The same situation happens when I want to check if eg "section_text" is empty. I just wish that a given component would not show up when it is empty or null


Solution

  • The way you are getting the section is not correct . This example works here because both your index and section happens to be 0 . But this will be an issue if your sectionId is 10 and the index in which it resides is 5. With your current code you will fetch the section in the index 10 .

    const section = data[car_id].sections.find(section => section.id === section_id);
    

    I think what you are looking for is conditional rendering .

    {
      section.image_left && (
        <div className="image_left">
          <img src={section.image_left} alt="" />
        </div>
      );
    }
    

    This renders the div only when there is a value in the section.image_left .