cft
Become a CreatorSign inGet Started

Conditional Rendering in React

Conditional rendering makes applications interactive and user-friendly, with conditional rendering developers can build applications that display content based on interaction with users. In this article you will find four different methods that can be applied for conditional rendering in react


user

Bishop ukpai

4 months ago | 9 min read
Follow

conditional-rendering-react-qczbc

As developers we most times want to render a certain page based on certain
conditions. For example, if a user is logged in, we might want to display “welcome” on the screen and if the user is not logged in then the message
should be “you are not logged in yet”.


This is possible with conditional rendering in react. Conditional rendering helps us display HTML pages based on some conditions, and they work pretty much like JavaScript conditions. There are four types of conditional rendering in react which includes, if/else statement, Element variable, Ternary condition operator, short circuit operator. We are going to have a good discussion on each of these methods, so you should expect to see the following in this article:

Outline


1)     The if/else conditions

2)     The use of Element variable

3)     Ternary condition operator

4)     Short circuit operator

5)     Conclusion

The if/else statement.

In react, developers can create a condition for displaying different items on the
browser, and one way we can achieve this is through the if/else condition.
There are certain steps we need to follow to apply this condition and they are:

1)First we need to create a .js file for our component

2)we have to create the component that will be rendered on the browser

3)We need to also add a state for our component

4) Finally define the if/else condition, and then import and render the component
in the App component.

So,
let’s try out these steps in our application. Let’s begin with creating a react
application. Run

“npx create-react-app tutorial”

To create the react application, and navigate to the project directory with

“cd tutorial”

Now open up the application in any code editor of your choice, for this tutorial I
have chosen to go with VScode, if I run

“code .”

The tutorial application will open in in VScode, so you should run the same command
too.

Now inside the code editor, we need to modify the application, so go over to the
App.js file and remove everything you have inside the App component’s return
keyword, leaving only the div tag, so your App component should now look like this:

import logo from './logo.svg';

import './App.css';

function App() {

return (

<div className="App">

</div>

);

}

export default App;

Ok, this is all we need for now save and close the file we will come back it later.
Now create a new folder and let’s call it “Component” and inside the component
folder we are going to create a file and call it “userstatus.js”. Ok pretty
cool, now inside the userstatus.js file we are going to create a class
component. So, just write down the codes below to create this component and
export it by default:

import React,{Component} from 'react'

class Userstatus extends Component{

}

export default Userstatus

For now, we don’t have to return anything, so we are going to define a state for
our component. This state will be the user’s log in status, whether the user is
logged in or not, we are going to set it to false by default. To do this we
have to make use of the constructor method, write out the code below inside the
Userstatus component:

constructor(props){

super(props)

this.state = {

loggedin: false

}

}

We are ready to apply the if/else condition. So, we say if the state of the user
is logged in the component should display “welcome”, else the component should
display, “You are not logged in”. Add a render method to the component, just
after the constructor method and then within the render method we will define
the if/else condition for our application. Add the code below to the Userstatus
components.

render(){

if (this.state.loggedin){

return <h1>Welcome</h1>

}

else{

return <h1>You are not logged in</h1>

}

}

Move over to App.js file and import the Userstatus with the code below:

import Userstatus from './Component/userstatus'

and render it in the App component with the code below:

<Userstatus/>

If you save the files and head over to the browser, you should see, ‘You are not
logged in”. This is because the status of our state was set to false, for our
application to display “Welcome” we need to set the state to true, well we can
achieve this by going up to where we defined the state and change it status
from false to true, well this will work and if you head over to the browser,
you will see that the message have changed to “welcome”, but this is not really
cool, what will make things more interesting is when our application changes
the message automatically on click of a button. Let’s add that effect quickly.
In the else statement, wrap everything in the return keyword inside a div tag and
then add a button element with “Log in”. Your code should look like this:

<div>

<h1>You are not logged in</h1>

<Button>Log in</Button>

</div>

Now in the opening tag of the Button element you need to add and onClick event and
bind it to an event handler, this event handler will be responsible for
changing the state of our component on click of the button. Let’s start by
setting the onClick event, add the line of code below in the opening Button
tag:

onClick ={this.statusChange}

We need to create the statusChange method, that changes the component’s status
from false to true, and this can be achieved by using the setState method.
Write out these lines of code above the render method to create the
statusChange method

statusChange = () =>{

this.setState({

loggedin: true

})

}

If you save the file and head over to the browser and click on the log in button
the message should change to “welcome”. With this we have successfully created a component that renders items based on conditions. One thing I want you to take note of is that the if/else statement cannot be used inside the return
keyword, but rather, the return keyword and corresponding JSX is passed into
the if/else statement. Now let’s look at other types of conditional rendering
we have in react

Element Variable

Another way we can create condition is through the use of element variable. In this approach we create a JavaScript variable that stores element and render them to the browser when certain conditions are satisfied.

This method involves the following steps:

1)Declaration of variable

2) State the appropriate element in the variable that you want to display based on conditions

3)Return the variable in the JSX.

So, inside the Userstatus component, clear out everything, in the render method, your code should be like this

class Userstatus extends Component{

constructor(props){

super(props)

this.state = {

loggedin: false

}

}

statusChange = () =>{

this.setState({

loggedin: true

})

}

}

export default Userstatus

Now we are going to going to define the render method and within this method we are going to declare a message variable, but for now we won’t assign any value to it. We will assign values to the message variable based on conditions. Write out the code below to define the render method and declare the message variable

render(){

let message

}

Now let define conditions for the message variable, this condition is defined with
the if/else statement. Within the render method add the if/ else block of code
below:

render(){

let message

if(this.state.loggedin){

message=<h1>Welcome</h1>

}

else{

message = <h1>Not logged in</h1>

}

If you save the file and check the browser you won’t see the message that we
defined, you will even get an error message. This is because we have not
defined a return statement for the render method, this is where the difference
between the if/else statement and the Element variable method comes in. In the
if/else statement the return statement is passed into the if and else blocks,
but in the element variable method, we pass the variable into the return
statement, so now let’s create the return statement inside the render method
and pass the message variable to it

return(

<h1>{message}</h1>

)

Now if you save the file and take a look at the browser you should now see “you are
not logged in displayed”. If you go back to VScode and change the state of our
component from false to true, then the message will change to “Welcome” or you
can assign the statuChange method to an onClick event in a button like we did
before, and you will get the same result.

Ternary Conditional Operator

This approach is quite handy compared to the other two methods I mentioned earlier and I strongly advise that you apply this method as much as possible, because it is way easier. In this method we pass three operators that gets evaluated, the first operator is evaluated to be either true or false, if it is true, then
the second operator is returned, but if the first operator is evaluated to be
false, then the third operator is rendered.

So, clear everything in the render method and return statement, your code should
look like the one below:

class Userstatus extends Component{

constructor(props){

super(props)

this.state = {

loggedin: false

}

}

statusChange = () =>{

this.setState({

loggedin: true

})

}

render(){

return

}

}

export default Userstatus

Now inside the return statement, we are going the add the Ternary conditional
operator, with the line of code below:

return this.state.loggedin? (<h1>Welcome</h1>):(<h1>you are not logged in</h1>)

What with this we just asked react to check if the loggedin state is true, if it is
then it should show the “Welcome” message in the browser else if it is false
then it should display “You are not logged in”. If you save the file and head
over to the browser, you should see “You are not logged in” displayed, if you
go back to VScode and change the status of the loggedin state to true, the
message should change to “welcome”.

You see that with this method you don’t need to write long lines of code, with just
a single line of code we were able to define our conditions and return
statement. Lastly on the list of condition rendering method we have the short
circuit operator, let’s take a good look at what it is

Short Circuit Operator

The short circuit method is just like a more specific approach of the Ternary conditional operator. For example, let’s say you have a case where you want to either display something or nothing then you make use of this method. This approach only makes use of a single condition. If the condition is evaluated to be true then the message is displayed, but if it false, nothing is displayed. To show an example of this, clear out everything you have in the return statement and add this instead

this.state.loggedin&&<h1>Welcome</h1>

if you save the file and head over to the browser, you will notice that there is
nothing in it, now go back to VScode and change the status of the loggedin
state to true, now go back and check, you should see welcome displayed. So that
is it with the short circuit operator approach, it is either true or nothing.
It does not accept a second parameter bolean value.

Conclusion

In one way or the other, developers make use of conditions to render certain html
pages and it make web applications interactive and functional. We have just
cover four simple conditional rendering methods we have in react, there are
other conditional rendering operators too but they are quite complex for
beginners, so in another article I am going to talk about them. Please
subscribe to get notification on new articles from us. See you next time.   







Upvote


user
Created by

Bishop ukpai

Follow

I am a software engineer


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles