Use && for a More Concise Conditional

Tell us what’s happening:
Describe your issue in detail here.

Hi everyone, I want to ask if my solution is a good way to solve this react exercise. I did it with a || operator, but i think that I am missing a concept. I saw the solution after solving the problem, but it’s in a little different way, using only the && operator.

  **Your code so far**

class MyComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    display: true
  }
  this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
  this.setState(state => ({
    display: !state.display
  }));
}
render() {
  // Change code below this line
  return this.state.display && (
     <div>
       <button onClick={this.toggleDisplay}>Toggle Display</button>
       <h1>Displayed!</h1>
     </div>
  ) || (
     <div>
       <button onClick={this.toggleDisplay}>Toggle Display</button>
     </div>
  );
}
};

Regards

  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36

Challenge: Use && for a More Concise Conditional

Link to the challenge:

Your solution works of course, but if you’ve already seen a lot of React code, normally you’d do it like in the example solution. There’s no need to repeat all the JSX for the <div> and the <button>, those render in both cases. The only difference is whether the <h1> is displayed or not, so it’s cleaner/more concise to put only that <h1> inside a conditional.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.