React: Render with an If/Else Condition

React: Render with an If/Else Condition


Hello everyone. I solved this challenge a few minutes ago following the instructions about the if/else statement that returns something different based on the boolean value of this.state.display. However, I came up with a different idea. Instead of using the return statement two times, I declared a const variable named message and when the value of this.state.display is true the message is “Displayed!” and when the value is false it becomes empty like this “”. Then I insert the variable in the h1 tag with curly braces as shown below. Is it considered a good practice or should it be avoided?? Thank you in advance.

My code:

class MyComponent extends React.Component {
  constructor(props) {
    this.state = {
      display: true
    this.toggleDisplay = this.toggleDisplay.bind(this);
  toggleDisplay() {
      display: !this.state.display
  render() {
    // change code below this line
    const message;
      message = "Displayed!";
      message = "";
    return (
         <button onClick={this.toggleDisplay}>Toggle Display</button>


That won’t work, you’re trying to reassign the variable message. It should be

const message = this.state.display ? 'Displayed' : '';

But yes, pattern is fine and very common. Once it goes beyond a single short return value, switch from a ternary to a function like

const message(display) {
  // Do logic here

Then when it get bigger, switch to a full component.


hello,what I know that you should not use const when you want to reassign a variable ,so here in your code you should use let or var instead and it will work .