physicsboy
physicsboy

Reputation: 6348

Perform conditional render operations on mapped data - React

I am mapping data within the returned render, but I am wanting to then perform a conditional on the data that has been mapped... Is it possible to do something like this?

export default function App() {
  const prod = [
    {'name': '1'},
    {'name': '2'},
    {'name': '3'}
  ];

  return (
    <div className="App">
      {prod && (
        <div>
          {prod.map(p => (

            // This is the point I get an error
            {p.name === '1' && (
              <h1>This is 1</h1>
            )}

          ))}
        </div>
      )}
    </div>
  );
}

Currently I am getting an error:

Unexpected token, expected "," (16:14)

  14 |         <div>
  15 |           {prod.map(p => (
> 16 |             {p.name === '1' && (
     |               ^

Upvotes: 0

Views: 35

Answers (2)

DBS
DBS

Reputation: 9984

Arrow functions with the format x => () return the content of the brackets.

So you are returning what the compiler thinks is an object, as it's wrapped in curly brackets x => ({ ... }) You need to remove the braces:

prod.map(p => (
    p.name === '1' && <h1>This is 1</h1>
)

Or explicitly return the value:

prod.map(p => {
    return p.name === '1' && <h1>This is 1</h1>
}

Upvotes: 1

Sifat Haque
Sifat Haque

Reputation: 6067

If you want to map the data for any specific index then you can check this.

<div>
    {prod.map(p => p.name === '1' && <h1>Conditionally Mapped</h1> || <h1>Normally mapped</h1>}
</div>

// similar to the previous one

<div>
    {prod.map(p => {
      if(p.name === '1') return <h1>Conditionally Mapped</h1>
      else return <h1>Normally mapped</h1>
    }

</div>



Upvotes: 0

Related Questions