skip to Main Content

So I have a component like which contains some data like headerImage = ‘image.jpg’ description = ‘lorem ipsum’ … ,and a builder component that takes these props and builds a page for each brand like this :

   `function IndividualBrand({headerImage,description ....}) {
   return <div>{description}</div>  ...etc
    }`

How can i conditionally render a prop if it exists in the brand component. Like ,if contains listDescription , then render {listDescription}

I have this builder component:

  `function IndividualBrand({
     headerImage,
     description,
     list,
     video,
     homeSite,
     videosArray,
    })`

and I try to conditionally render something like this :

   ` {list !== undefined(
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: "1.3rem",
            }}
          >
            <ul style={{ fontSize: "1.3rem", marginLeft: "1.3rem" }}>
              {list}
            </ul>
          </div>
        )}`

but I get an error like undefined is not a function

2

Answers


  1. You can use a conditionaly render in your component:

    return (<div>
      {!!listDescription && <MyListDescriptionComponent {... props} />}
    </div>)
    

    If listDescription does not exists, is undefined, null, etc… it will not be rendered, if it exists so your component will be rendered as normal.

    Login or Signup to reply.
  2. Apparently you are missing double ampersand (logical AND) when rendering your JSX.

    {list !== undefined && (
       <div>
         ...
       </div>
    )}
    

    that can be shortened to:

    {list && (
       <div>
         ...
       </div>
    )}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search