PandaMastr
PandaMastr

Reputation: 695

Can i use multiple state value inside conditional rendering - ReactJs

I wonder how can use two state based booleans inside of the conditional rendering . For example i want to render a certain <div> element if one of the conditions are truthy and otherwise don't render it Example :

{
 this.state.visible && this.state.checked &&
 <div>
  ...
 </div>
}

In order to display my error message i use this example , but init i have the .length of the object so it is easy to use like :

 {
  this.state.ErrorMessage.length > 0 &&
 <p>Error 404</p>
 }

Can somebody give me heads up ? I am a little bit confused .

Upvotes: 0

Views: 1048

Answers (2)

Japar Sathik
Japar Sathik

Reputation: 121

Use it as a separate function which returns the components based on condition.

Example :

renderConditionalComponent() {
  const { visible, checked } = this.state;

  if (visible || checked) {
    return <Component1 />;
  }

  // There could be other condition checks with different components.
  // ...

  return null;
}

render() {
  // ...
  return (
    <div>
      {this.renderConditionalComponent()}
      {/* other components, etc */}
      <OtherComponent />
    </div>
  );
}

Upvotes: 0

DEEPAK
DEEPAK

Reputation: 1504

You can follow your way by parenthesis, to check both are true:

{
    (this.state.visible && this.state.checked) &&  <div>...</div> 
}

if you want one of is true:

{
    (this.state.visible || this.state.checked) &&  <div>...</div> 
}

Upvotes: 2

Related Questions