简体   繁体   中英

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>);
  }

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>
      );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM