简体   繁体   中英

React: How to conditionally render?

I have three components A, B & C.

I have two flags showA & showB.

  • If ShowA and ShowB are false then render C.
  • If ShowA is true only then render A.
  • If showB is true only then render B.

How do i achieve this?

You can achieve it in different ways.

Multiple returns

render() {
    const { showA, showB } = this.state;
    if (showA) return <A />
    if (showB) return <B />
    return <C />
}

Inline if with the '&&' operator

render() {
    const { showA, showB } = this.state;
    return (
        <div>
            {(showA && !showB) && <A />}
            {(showB && !showA) && <B />}
            {(!showA && !showB) && <C />}
        </div>
    )
}

See also: https://reactjs.org/docs/conditional-rendering.html

  class APP extends React.Component {
    constructor() {
      super();
      this.state = { showA: false, showB: false };
    }

    render() {
      const {showA, showB} = this.state;
      return [showA && <A/>, showB && <B />];
   }
 }

I guess you meant show C component when showA and showB are both false

Assuming that your showA and showB are state properties:

render() {
  return (
    this.state.showA 
    ? <A />
    : this.state.showB ? <B />
    : <C />
  )
}

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