Rendering Conditionals in React
Tags: react, beginners, javascript, tutorial
Published: 2020-10-16 22:09:11

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](https://dev-to-uploads.s3.amazonaws.com/i/nfwy7fxcy0kkbcujc9rs.png)
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>
  );
}
```
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;
```
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>
```
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
  }
...
```
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](https://reactjs.org/docs/handling-events.html) and:
```
<button onClick={this.toggleHandler}>Toggle</button>
```
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})
  }
```
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)**
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>
```
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> 
        }
```
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>
```
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;
```
**2. [JS if statements](https://www.w3schools.com/js/js_if_else.asp)**
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 (...
```
Then we use a traditional if statement:
```
render() {

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

    return (...
```
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>
```
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>
    );
  }
}
```
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>
    );
```
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;
```
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!