0

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 .

1
  • 3
    To check if one of them are truthy you can use ||: (this.state.visible || this.state.checked) && <div>...</div> Commented Nov 26, 2019 at 10:44

2 Answers 2

2

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> 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yep mate the second expression does the job !
0

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

2 Comments

The question was about the ternary operators .
@PandaMastr your question is about conditional rendering, not about ternary. You even accepted an answer that doesn't use ternary at all, you're not mentioning ternary in your question, etc. This answer is a valid way to achieve conditional rendering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.