Ciprian
Ciprian

Reputation: 3226

Display content based on function return in ReactJS

I am creating a grid of elements and need to add a row element based on the index of the element being rendered. So I have something like this:

const checkIndex = (index) => {
  ...
  //return either true or false
}

return (

  data ? data.map((item, index) => (

    <div className="wrapper">
     <div className="row">
      <div className="col">Title</div>
     </div>
    </div>

  )
)

So I need to display the row element based on the index

I tried something like this but it doesn't seem to work ...

{checkIndex(index) ? '<div className="row">' : ''}
{checkIndex(index) && '<div className="row">'}

Upvotes: 1

Views: 62

Answers (2)

Raicuparta
Raicuparta

Reputation: 2115

It didn't work because you are using a string representation of the element, instead of the actual element.

return (
  data && data.map((item, index) => (
    <div className="wrapper">
     {checkIndex(index) && (
       <div className="row">
         <div className="col">Title</div>
       </div>
     )}
    </div>
  )
)

Also note how I replaced data ? with data &&. ? is the ternary operator, so you'd need a : after it. More about it here.

Upvotes: 4

Naved Khan
Naved Khan

Reputation: 1947

 return (
    data ? data.map((item, index) => (
            <div className="wrapper">
             <div className="row">
              <div className="col">Title</div>
             </div>
            </div>
          ) : <h2>Sorry data Not available</h2>
        )

Upvotes: 1

Related Questions