edmamerto
edmamerto

Reputation: 8165

How to do condtitional rendering in React and ES6 inside the map function

I'm trying to render an array of messages but would want it to render differently by class given a condition my code looks like this:

render() {
      return (
      <div>
      {this.props.messages.map((m, index) => (
          //if m.id === 1 render this:
          <p className={someClass1}>Hello, {m.message}!</p>
          //else render this:
          <p className={someClass2}>Hi, {m.message}!</p>
      ))}
      </div>);
  }

Upvotes: 0

Views: 49

Answers (1)

John Ruddell
John Ruddell

Reputation: 25862

you can easily add logic to your map. you just need the contents to not be an inline return of a react component.

render() {
    return (
        <div>
            {this.props.messages.map((m, index) => {
                if (m.id === 1){
                    return <p className={someClass1}>Hello, {m.message}!</p>
                }
                return <p className={someClass2}>Hi, {m.message}!</p>
            })}
        </div>
      );
  }

You can also do the same thing with a forEach outside of the return on your render like so

render() {
    const elems = [];
    this.props.messages.forEach( (m, index) => {
        if (m.id === 1) {
            elems.push(<p className={someClass1}>Hello, {m.message}!</p>);
        } else {
            elems.push(<p className={someClass2}>Hi, {m.message}!</p>);
        }
    return (
        <div>
            {elems}
        </div>
      );
  }

Upvotes: 2

Related Questions