Search code examples
javascriptreactjscomponents

Show two React Component in IF ELSE condition


In React App.js i have condition if false then show two component if false show third component but i am not able to pass two component if condition is false

{ !this.state.imageView ?
              (  <OneComponent/> && <TwoComponent/>)
                 : // else
                  <ThridComponent />
              }

Solution

  • You need to wrap your two components with a single element.

    If you don’t need an additional element, such as a <div>, then you can use a fragment for this:

    {!this.state.imageView
      ? (
        <>
          <OneComponent/>
          <TwoComponent/>
        </>
      )
      : (
        <ThridComponent />
      )
    }
    

    Note, the above <>...</> syntax is shorthand for:

    {!this.state.imageView
      ? (
        <React.Fragment>
          <OneComponent/>
          <TwoComponent/>
        </React.Fragment>
      )
      : (
        <ThridComponent />
      )
    }
    

    You can read more about fragments here:
    https://reactjs.org/docs/fragments.html