0

I want to use an if statement inside a map, but i dont want to switch the return. Code:

this.example = this.state.data.map((item) => {
    return(
        <div>
        {if(1 + 1 == 2){
            data here
        }}
        </div>
    )
})

I get that i dont understand how to use these inside of react. But basically, i need to return a link based on a logo that is returned inside the map. So if its logo A, then return Link A, Logo B, Link B, etc.

The logo is being mapped through an api, the link is not.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Josh Winters
  • 829
  • 5
  • 12
  • 27
  • 1
    While you *could* do this with a ternary, that you add "etc." leads me to believe this is an awful idea. Use a map of logos to URLs. – Dave Newton Jul 29 '19 at 13:09

2 Answers2

2

Use ternary operators:

this.example = this.state.data.map((item) => {
    return(
        <div>
            {link ? <img src={link} /> : null}
        </div>
    )
})
Dupocas
  • 20,285
  • 6
  • 38
  • 56
0

You have a couple of options here:

1) Use if statement with return value inside the callback passed to .map method

2) Use ternary operators as @Dupocas has mentioned

Example of the first option:

const nodeExample = this.state.data.map((item) => {
  if (item.visibleExample) {
    return (
      <div>{item.titleExample}</div>
    );
  }
  return <div>Example is not visible</div>
});

Example of more appropriate (in your case) usage:

const nodeExample = this.state.data.map((item) => (
  <div>
    {item.visibleExample ? item.titleExample : 'Example is not visible' }
  </div>
));

Hope this helps.

InkFaust
  • 16
  • 3