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.

1
  • 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. Commented Jul 29, 2019 at 13:09

2 Answers 2

2

Use ternary operators:

this.example = this.state.data.map((item) => {
    return(
        <div>
            {link ? <img src={link} /> : null}
        </div>
    )
})
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

normally i would use a ternary, but in this case there can be 4 options.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.