Getting Started:
Conditional rendering in React works the same way as conditional rendering in Javascript. Let us create a sample project to understand the concept. After creating a React App, open App.js in the code editor and create an App component. Now let's look at the different ways to achieve conditional rendering in React.
If/else statements
In programming, whenever we come across the word conditional, we automatically think of the if-else statement. This statement works in a very similar way in React as well.
render() function decides the view visible to the user in ReactJS, so conditional statements will be applied to that part of the code. Statements that should be interpreted before rendering are specified using curly braces {} in JSX. If-else statements can be applied in the following way.
Note: if-else statements do not work inside JSX. Hence, we use them outside of the JSX to determine which components are to be used.
Code:
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
LoggedIn: true
};
}
render() {
return (
<div className="App">
<h1>
Let us understand conditional rendering in React.js
</h1>
<button>Login</button>
<button>Logout</button>
</div>
);
}
}
export default App;
Output
As you can see, we have created a React application that shows two buttons. Our task is to make sure that only one of the buttons is visible to the user at a specific time. Let’s see how this can be done.
Code:
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
LoggedIn: false
};
}
render() {
let {LoggedIn} = this.state;
// when LoggedIn state is true
if (LoggedIn) {
return (
<div className="App">
<h1>
Let us understand conditional rendering in React.js
</h1>
<button>Logout</button>
</div>
);
} else { // when LoggedIn state is false
return (
<div className="App">
<h1>
Let us understand conditional rendering in React.js
</h1>
<button>Login</button>
</div>
);
}
}
}
export default App;
Output
If we had initialized the LoggedIn state as true, the user would have seen the logout button.
Note: if-else statements do not work inside JSX. So, we use them outside of our JSX to determine the components that are going to be used.
Using Element Variables
Element variables are just variables that hold the value of the JSX element. We can change the values that they have according to our condition.
Code:
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
LoggedIn: true
};
}
render() {
let { LoggedIn } = this.state;
let Button;
// When loggedin state is true
if (LoggedIn) {
Button = <button>Logout</button>;
}
// When Loggedin state is not true
else {
Button = <button>Login</button>;
}
return (
<div className="App">
<h1>
Let's use element variables!
</h1>
{Button}
</div>
);
}
}
export default App;
The value of the component Button is assigned according to our condition.
Using logical &&
Logical && is a simple programming concept that is used to implement conditions. This case is very similar to our if-else condition. Let us look at its implementation in the render function.
Code:
render() {
let { LoggedIn } = this.state;
return (
<div className="App">
<h1>
Let us understand conditional rendering in React.js
</h1>
// True && expression evaluates to expression
{LoggedIn && <button>Logout</button>}
</div>
);
}
}
If the LoggedIn condition is true, the user can see the Logout button. Otherwise, the condition will be ignored entirely.
Using the conditional operator (Inline if-else)
The conditional operator or the ternary operator is a frequently used shortcut for the if-statement. It takes three operands. The first operand is for the condition, and the other two are for the options.
The syntax for the ternary operator is a condition followed by a question mark, an expression to execute if the condition is true followed by a colon(:), then the expression to execute if the condition is false.
Syntax:
condition ? true case : false case
Let's have a look at the code.
Code:
render() {
let { LoggedIn } = this.state;
return (
<div className="App">
<h1>
Let us understand conditional rendering in React.js </h1>
// If LoggedIn is true then logout button else login button
{LoggedIn ? <button>Logout</button> : <button>Login</button>}
</div>
);
}
}
As we can see, we have two options for our condition LoggedIn.
Switch statement
If multiple conditions are present, then if-statement is not the best way to go as it may reduce performance. In such cases, we can use switch statements. To avoid re-rendering, let us create another file called AuthButton.js, in which we will implement our switch statement.
Code:
import React from "react";
const AuthButton = props => {
let { LoggedIn } = props;
switch (LoggedIn) {
case true: // LoggedIn state is true
return <button>Logout</button>;
break;
case false: // LoggedIn state is false
return <button>Login</button>;
break;
default:
return null;
}
};
export default AuthButton;
Now, we just have to return the output of our code in our main code.
Code:
import React, { Component } from "react";
import AuthButton from "./AuthButton";
class App extends Component {
constructor(props) {
super(props);
this.state = {
LoggedIn: true
};
}
render() {
let { LoggedIn } = this.state;
return (
<div className="App">
<h1>
Let us understand conditional rendering in react.js
</h1>
<AuthButton LoggedIn={LoggedIn} />
</div>
);
}
}
export default App;
Enums
Using enums, we can define a set of named constants. In our example, we have two states, logged in and logged out. We will create a map of key-value pairs using enum. Let's see how to use enums for conditional rendering in React.
Code:
// Create components for each state
const Login = () => {
return <button>Login</button>;
};
const Logout = () => {
return <button>Logout</button>;
};
// Create an object that can be used as an enum
const ENUM_STATES = {
Login: <Login />,
Logout: <Logout />
};
// Create a function that will return components based on state
function EnumState({ state }) {
return <div>{ENUM_STATES[state]}</div>;
}
// Create a component that will pass our states to the above function
class Card extends React.Component {
render() {
return (
<div>
<h1>Let us understand conditional rendering in React.js</h1>
<EnumState state="Login"></EnumState> // state is set as log in
</div>
);
}
}
ReactDOM.render(<Card />, document.getElementById("app"));
Check out Advantages of React JS here.
Frequently Asked Questions:
1. How to hide a component even though another component rendered it?
Ans- Simply specify the return type as NULL for that function. Like in the above case, return type is a button, we can specify it as NULL instead.
2. When to use conditional rendering in React.js?
Ans- We use conditional rendering when the visibility of a particular UI component, like a button, depends on a specific condition. You can get detailed information here.
3. How do I conditionally render an image in React?
Ans- We can achieve this by checking if the image tag is valid. The method would be the same as discussed above.
4. Why should re-rendering be avoided?
Ans- Re-rendering significantly affects the performance of your code; hence we should avoid it as much as possible.
5. What is the best method to implement conditional rendering?
Ans- This is entirely dependent on the programmers' preference. You can make this decision yourself by considering your programming style, the complexity of code logic, and your comfort.
Key Takeaways:
In this blog, we discussed conditional rendering in React. We looked at four primary methods: if/else statements, element variables, logical &&, ternary operator, switch statements, and enums.
Developers, if you are preparing for the following interview, check out the blogs 15 Most Frequently Asked React JS Interview Questions and 10 Best ReactJS Interview Questions. And if you are a beginner, check out the Top 5 skills to learn before starting with ReactJs to know the prerequisites to learn React.
You can also consider our React Js Course to give your career an edge over others.
We hope you found this blog helpful. Feel free to let us know your thoughts in the comments section.