Rendering Conditionals in React

rwparrish

rwparrish

Posted on October 16, 2020

Rendering Conditionals in React

In this blog, I will cover how to render conditionals in a React app. This is meant to be a short n' sweet, lean n' mean code along. You'll watch conditionals you created work right in front of your own eyes! You will also learn some other little React tips that I have picked up so far.

In my first blog post in this series, I encouraged you to use CodePen. There is nothing wrong with CodePen but in the spirit of learning let's get familiar with other resources out there as well.

Google 'codesandbox' and you should see this:
Alt Text
Now click on "React". Notice on the left-hand side under dependencies that react, react-dom, and react-scripts are all taken care of for us already. Sweet, let's build!

First, we will need to convert the functional component given to us to a class-based component:
This:

import React from "react";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Becomes this:

import React, { Component } from "react";
import "./styles.css";

class App extends Component {


  render() {
    return (
      <div className="App">
        <h1>Hi, I'm Ryan...</h1>
        <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
        <h2>Let's overcome that feeling and learn together!</h2>
      </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

You can see that I added an <h2> and changed the text inside the tags. Feel free to change it to whatever you want. Let's say that we want the ability to toggle whether or not the three elements inside the div render. We could do this using a button... and we will! Also, I will cover two different approaches to outputting content conditionally in a React app.

Let's make the button first:

<div className="App">
        <button>Toggle</button>
        <h1>Hi, I'm Ryan...</h1>
        <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
        <h2>Let's overcome that feeling and learn together!</h2>
      </div>
Enter fullscreen mode Exit fullscreen mode

Because we want to be able to change some state in our app dynamically we need to add state:

class App extends Component {

  state = {
    showText: false
  }
...
Enter fullscreen mode Exit fullscreen mode

I named the property "showText" but you could name it whatever you want. Notice that its initial value is set to 'false.' We want our button to be able to toggle the "showText" value essentially. To do this we want the button to call a method that changes state when it is clicked. So we add an "onCLick" event handler and:

<button onClick={this.toggleHandler}>Toggle</button>
Enter fullscreen mode Exit fullscreen mode

Next, we should build the method that will change the state, i.e., change the value of the property "showText" after the button is clicked:

toggleHandler = () => {
    const doesShow = this.state.showText
    this.setState({showText: !doesShow})
  }
Enter fullscreen mode Exit fullscreen mode

Above a variable "doesShow" is defined and assigned a value of "false". It is important to note here that this.state.showText is the same as "false" because "showText" in the state was given an initial value of false. Then the setState method is used to change the value of "showText" to the opposite of "doesShow" - that's where the "!" bang operator comes in. Each time we click the button we made, the value of "showText" will be changed to its opposite value. This is true because "doesShow" is assigned a boolean value of "false" initially.

OK, now with all that set up let's look at a couple of different ways to implement our conditional statements into this code. Remember, we want the text to appear and disappear when our button is clicked.

1. Ternary Operators
First we should wrap everything we want to toggle inside a div:

          <div>
            <h1>Hi, I'm Ryan...</h1>
            <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
            <h2>Let's overcome that feeling and learn together!</h2>
          </div>
Enter fullscreen mode Exit fullscreen mode

It is possible to wrap the element that we want to output conditionally with curly braces {} - that would be all of the above code:

        { 
          <div>
            <h1>Hi, I'm Ryan...</h1>
            <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
            <h2>Let's overcome that feeling and learn together!</h2>
          </div> 
        }
Enter fullscreen mode Exit fullscreen mode

Now we can add our ternary conditional logic inside the curly braces:

<div className="App">
        <button onClick={this.toggleHandler}>Toggle</button>
        { this.state.showText ?
          <div>
            <h1>Hi, I'm Ryan...</h1>
            <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
            <h2>Let's overcome that feeling and learn together!</h2>
          </div> : null
        }
      </div>
Enter fullscreen mode Exit fullscreen mode

In the code above we can see that if this.state.showText evaluates to true then we should see text rendering and if it evaluates to false we should see nothing. The ternary operator uses : to handle the else case as you can see above - : null basically means "else nothing".

If everything is working correctly, you should see no text until you click the button. Then, each time you click it thereafter the text should toggle! Pretty neat, huh!?

If you are having issues please check out the full code below:

import React, { Component } from "react";
import "./styles.css";

class App extends Component {

  state = {
    showText: false
  }

  toggleHandler = () => {
    const doesShow = this.state.showText
    this.setState({showText: !doesShow})
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.toggleHandler}>Toggle</button>
        { this.state.showText ?
          <div>
            <h1>Hi, I'm Ryan...</h1>
            <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
            <h2>Let's overcome that feeling and learn together!</h2>
          </div> : null
        }
      </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

2. JS if statements
Using the if statement approach is generally the preferred approach to outputting conditional content in React; especially when dealing with larger apps. We already know that we are making changes to the state each time we click the button we built. React also keeps track of any changes being made to the state and will actually call the render method each time the state changes to be sure the content rendered is current. Knowing this fact, we can try the following approach to outputting conditional content.

Inside the render method but above the return define a variable and assign it null:

render() {

    let text = null

    return (...
Enter fullscreen mode Exit fullscreen mode

Then we use a traditional if statement:

render() {

    let text = null
    if (this.state.showText) {
      text = ()
    }

    return (...
Enter fullscreen mode Exit fullscreen mode

In the above code, whenever this.state.showText evaluates to true because of our button click causing a change in state, the "text" variable will be assigned a value of:

<div>
          <h1>Hi, I'm Ryan...</h1>
          <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
          <h2>Let's overcome that feeling and learn together!</h2>
        </div>
Enter fullscreen mode Exit fullscreen mode

So cut the above code out of the return and stick in between the parentheses that are assigned to "text" in the if statement block like this:

render() {

    let text = null
    if (this.state.showText) {
      text = (
        <div>
          <h1>Hi, I'm Ryan...</h1>
          <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
          <h2>Let's overcome that feeling and learn together!</h2>
        </div>
      )
    }
    return (
      <div className="App">
        <button onClick={this.toggleHandler}>Toggle</button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

The last thing we need to do is dynamically render the "text" variable in the return like this:

return (
      <div className="App">
        <button onClick={this.toggleHandler}>Toggle</button>
        {text}
      </div>
    );
Enter fullscreen mode Exit fullscreen mode

After completing this step your button should toggle the text rendering or not. If something has gone wrong, check the full code below:

import React, { Component } from "react";
import "./styles.css";

class App extends Component {

  state = {
    showText: false
  }

  toggleHandler = () => {
    const doesShow = this.state.showText
    this.setState({showText: !doesShow})
  }

  render() {

    let text = null
    if (this.state.showText) {
      text = (
        <div>
          <h1>Hi, I'm Ryan...</h1>
          <h2>I am learning to code and I too get overwhelmed sometimes with all there is to learn...</h2>
          <h2>Let's overcome that feeling and learn together!</h2>
        </div>
      )
    }
    return (
      <div className="App">
        <button onClick={this.toggleHandler}>Toggle</button>
        {text}
      </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Nice! In this little code along you learned how to output conditional content using two different approaches - (1)ternaries and (2)if statements. Hopefully, you enjoyed yourself while gaining some knowledge and experience. If you enjoyed this and found it to be useful, please share and give feedback. If you think you can explain something better than I did, school me in the comments!

Cheers!

💖 💪 🙅 🚩
rwparrish
rwparrish

Posted on October 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related