The ability to generate different user interface (UI) markups depending on whether a condition is true or not is known as conditional rendering. So, this React JS tutorial will revolve around how to implement condition rendering in react js.
Moreover, we will also illustrate a variety of different examples related to react conditional rendering. Here is the complete list of examples that we are going to discuss.
- What is conditional rendering in React js
- How to do conditional rendering in react class component
- How to do conditional rendering in react functional component
- Conditional rendering react hooks
- Conditional rendering react ternary
- How to do conditional rendering array in React js
- Conditionally render attribute react
- React conditional rendering vs display none
- React conditional rendering and operator
- React conditional rendering empty array
- React avoid conditional rendering
- conditional rendering react button
- conditional rendering react radio button
- react conditional rendering based on screen size
- conditional rendering react two conditions
- react conditional rendering displays 0
- react conditional rendering enum
- conditional rendering react multiple elements
- react conditional rendering for loop
- conditional rendering react router
- react conditional rendering based on URL
- react conditional rendering fade out
- conditional rendering react props
- react conditional rendering props.children
- react conditional rendering parent
- react conditional rendering breakpoint
What is conditional rendering in React js?
React’s conditional rendering functions similarly to JavaScript’s conditions. Create elements that describe the current state using JavaScript operators like if or the conditional operator and let React modify the UI to match them.
Let’s understand conditional rendering with an example:
Think about how you would handle a login/logout button. Given that the two buttons serve distinct purposes, they will each be a separate component.
The task at hand is to render the Logout component to display the logout button if a user is currently logged in, and the Login component to display the login button if they are not. In ReactJS, this is referred to as Conditional Rendering.
To do this, generate a number of components and render them in accordance with certain criteria. React also supports this form of encapsulation.
There are different ways to handle those cases in conditional rendering:
- if/else
- Ternary operation
- Inline IF with Logical AND operator
Conditional rendering in React Class component
Here we will see how to apply conditional rendering in react Class component.
We will use the above example to see how to do conditional rendering in React Class component.
In order to accomplish this, we will develop a parent component called “Homepage,” two child components called “Login” and “Logout,” and a fourth component called “Message.” To keep track of whether a user is logged in or not, we will utilize a state variable called “isLoggedIn”.
Whenever the user clicks the button, the value of this variable will change. Depending on the value contained in isLoggedIn, the Homepage component will render the Message component to display the message and one of the Logins or Logout components as well.
The message component returns various messages dependent on the value of the isLoggedIn state.
Let’s say the index.html contains the below code
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import Homepage from './Homepage';
function App() {
return (
<div className="App">
<Homepage></Homepage>
</div>
);
}
export default App;
Next, the Homepage contains the below code:
import React from 'react';
import Message from './Message';
import Login from './Login';
import Logout from './Logout';
class Homepage extends React.Component{
constructor(props)
{
super(props);
this.state = {isLoggedIn : false};
this.loginClicked = this.loginClicked.bind(this);
this.logoutClicked = this.logoutClicked.bind(this);
}
loginClicked()
{
this.setState({isLoggedIn : true});
}
logoutClicked()
{
this.setState({isLoggedIn : false});
}
render(){
return(
<div>
<Message isLoggedIn = {this.state.isLoggedIn}/>
//ternary operator is used
{
(this.state.isLoggedIn)?(
<Logout onClickFunc = {this.logoutClicked} />
) : (
<Login onClickFunc = {this.loginClicked} />
)
}
</div>
);
}
}
export default Homepage;
Next, the Message.js component contains the below set of code:
import React from 'react';
function Message(props)
{
if (props.isLoggedIn)
return <h1>Welcome User</h1>;
else
return <h1>Please Login</h1>;
}
export default Message;
And Login component contains the below code:
import React from 'react';
function Login(props)
{
return(
<button onClick = {props.onClickFunc}>
Login
</button>
);
}
export default Login;
Logout component contains the below code:
import React from 'react';
function Logout(props)
{
return(
<button onClick = {props.onClickFunc}>
Logout
</button>
);
}
export default Logout
Now run the application with the npm start command, you can see one button with the message is rendered on the page. Click on the log in it will show you ‘Welcome user’ and Log out button. Then click on Logout Button it will render the Login component.

Read Handling Events in React js
Conditional rendering in react functional component
Here we will see how to do conditional rendering in react functional component.
As we have two child components Login and logout, to keep track of whether the user is logged in or not, we will use isLoggedIn. If the isLoggedIn is true, then it will return the Login message, if it is false then it returns the log-out message.
Let’s say the index.html contains the below code
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js component contains the below code: in this, we are passing the value to the Homepage component. Based on the passed value login and logout will render on the page.
import './App.css';
import Homepage from './Homepage';
function App() {
return (
<div className="App">
<Homepage isLoggedIn={false} />
</div>
);
}
export default App;
The homepage component contains the below code:
import React from 'react';
import Login from './Login';
import Logout from './Logout';
function Homepage(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <Login />;
}
return <Logout />;
}
export default Homepage;
The Login component contains the below code:
import React from 'react';
function Login(props)
{
return(
<>
<h1> Please Log in</h1>
</>
);
}
export default Login;
The Logout component contains the below code:
import React from 'react';
function Logout(props)
{
return(
<>
<h1> Welocome user</h1>
</>
);
}
export default Logout
Now run the application with npm start command and you can see the result ‘Welcome user’ render on the page, as the passed value is false.

Conditional rendering react hooks
Here we will see conditional rendering with react hooks.
As we have two child components Login and logout, to keep track of whether the user is logged in or not, we will use isLoggedIn. If the isLoggedIn is true, then it will return the Login message, if it is false then it returns the log-out message.
Conditional rendering: if else
Let’s say the index.html contains the below code
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import Homepage from './Homepage';
function App() {
return (
<div className="App">
<Homepage />
</div>
);
}
export default App;
The Homepage.js component contains the below code: here we are passing the value to the login component and logout component.
import React from 'react';
import { useState } from 'react';
import Login from './Login';
import Logout from './Logout';
const Homepage = () => {
const [isLoggedIn, setIsLoggedIn] = useState(true);
if (isLoggedIn) {
return <Login>Login</Login>;
} else {
// If user is logged out
<h1>You are out</h1>
return <Logout>Logout</Logout>;
}
};
export default Homepage;
The Login component contains the below code:
import React from 'react';
function Login(isLoggedIn)
{
return(
<>
<h1> Please Log in</h1>
</>
);
}
export default Login;
The Logout components contains the below code:
import React from 'react';
function Logout(isLoggedIn)
{
return(
<>
<h1> You are in ✌</h1>
</>
);
}
export default Logout
Now run the application with the npm start command, and you can see the ‘You are in’ message is rendered on the page, as the passed value is true.
Conditional rendering: ternary operator
Here change the Homepage.js component with the below code:
import React from 'react';
import { useState } from 'react';
import Login from './Login';
import Logout from './Logout';
// change the value of useState from true to false
const Homepage = () => {
const [isLoggedIn, setIsLoggedIn] = useState(true);
return (
<div>
{isLoggedIn ? <Logout>Logout</Logout> : <Login>Login</Login>}
</div>
);
}
export default Homepage;
Now run the application with the npm start command, and you can see the output as’ You are in ‘, as the passed value is true.

Read State in React js
Conditional rendering react ternary
Here we will see how to do conditional rendering with the react ternary operator.
It is possible to use the ternary conditional operator in place of an if…else block:
condition? expression for true: expression for false
Example: React Conditional rendering with the ternary operator in Class component
Here we’ll construct a component with the view and edit capabilities.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import React from 'react';
import {Component} from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {text: '', inputText: '', mode:'view'};
this.handleChange = this.handleChange.bind(this);
this.handleSave = this.handleSave.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}
handleChange(e) {
this.setState({ inputText: e.target.value });
}
handleSave() {
this.setState({text: this.state.inputText, mode: 'view'});
}
handleEdit() {
this.setState({mode: 'edit'});
}
render () {
const view = this.state.mode === 'view';
return (
<div className='App'>
<p>Text: {this.state.text}</p>
{
view
? null
: (
<p>
<input
onChange={this.handleChange}
value={this.state.inputText} />
</p>
)
}
<button
onClick={
view
? this.handleEdit
: this.handleSave
}
>
{view ? 'Edit' : 'Save'}
</button>
</div>
);
}
}
export default App;
Now run the application with the npm start command, and you can see the Edit button with Text. Next, click on the Edit button, and you can see the Text box arrived. Then write something and click on save, and you can see the text.

Example: React Conditional rendering with the ternary operator in Functional component
Here we will construct a component, that will check whether the number is greater or smaller.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import React from 'react';
function App(){
const num= 5;
return(
<div className='App'>
<h1><b>The number is {num>4?"greater!":"smaller!"}</b></h1>
</div>
)
}
export default App;
Now run the application with npm start command and you can see the The number is greater rendered on the page as 5 is greater than 4.

Read Props in React js
React conditional rendering array
Here we will see how to conditionally render an array in the React js.
For example, if there isn’t a list of items to display in the first place, a List component in React shouldn’t render the list of HTML elements in a view. To return earlier, simply use an if statement in JavaScript.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import React from 'react';
import List from './List';
const employee= [{ id: '3', firstName: 'Rocky', lastName: 'Vinsen' },
{ id: '4', firstName: 'Jay', lastName: 'Shetty' },
]
function App() {
return (
<div className='App'>
<h1>List of employee</h1>
<List list={employee} />
</div>
);
}
export default App;
The List component contains the below code:
import React from 'react';
import Item from './Item';
function List({ list }) {
// if there is no list then it will return null else list of items
if (!list) {
return null;
}
return (
<ul>
{list.map(item => (
<Item key={item.id} item={item} />
))}
</ul>
);
}
export default List;
And the item contains the below code:
import React from 'react';
function Item({ item }) {
return (
<li>
{item.firstName} {item.lastName}
</li>
);
}
export default Item;
Now run the application, with the npm start command and you can see the List of employees render on the page:

Conditionally render attribute react
Here we will see how to use conditional attributes in React component.
To create dynamic behaviors, conditional attributes are frequently utilized with React nowadays. However, most developers are not familiar with all the available implementation techniques.
Now we will discuss different types of methods of using conditional attributes or with react.
Method 1: Rendering conditional attributes in React
We should comprehend how conditional attributes are rendered by React’s underlying design before going on to the implementation.
In JavaScript, if you give an attribute a false value, the DOM will no longer contain that particular attribute. The DOM will not store an attribute if we set it to null, undefined, or false.
For instance, an attribute will be removed from the DOM if it is set to null, undefined, or false.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js contains the below code:
import './App.css';
import React from 'react';
function App() {
const require= true;
const notRequire= false;
return (
<div className='App'>
<input type="text" disabled={notRequire} required={require}/>
</div>
);
}
Now run the application with the npm start command, and you can see the input box. Then write something in the box. As input type is required, so we can add text to the input box.

Conditional attributes in if else
One of the simplest methods to use conditional characteristics is to use if-else statements. It is readable and largely uncomplicated.
Take a look at the example below, where users with the role of “Student” are prevented from using the input area. The user object’s role will be verified, and the input element will be adjusted as necessary.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js contains the below code:
import './App.css';
import React from 'react';
// import {Component} from 'react';
const App = () => {
let disabled = false;
let type = "text";
let name = "name";
const user = {
role: 'Student',
name: 'Ron',
}
if(user.role === 'Employee') {
disabled = true;
}
return <div className='App'>
<p>Write something if you are not Student</p>
<input type={type} name={name} disabled={disabled}/>
<p> name: {user.name}</p>
</div>
}
export default App;
Now run the application with npm start command and you can see the h1 text and input box render on the page. If the user role is equal to the student, then the text box is disabled, as it is an employee so we can write the name.

React conditional rendering vs display none
Here we will see how to set CSS display: none conditionally in React.
For example, we will create a component,
Keep a boolean in the state that represents whether or not the element should be displayed.
Set the element’s style prop’s display property with conditions.
To store a boolean that specifies whether or not an element should be displayed, we utilized the useState hook.
The isShown boolean value is toggled each time the button element is clicked, but this could also happen in other ways.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js contains the below code:
import {useState} from 'react';
import './App.css';
function App() {
const [isVisible, setIsVisible] = useState(true);
const handleClick = event => {
// 👇️ toggle visibility
setIsVisible(current => !current);
};
return (
<div className='App'>
<p>Click on the button </p>
<button onClick={handleClick}>Toggle visibility</button>
<div className={`my-class ${isVisible ? 'display-block' : 'display-none'}`}>
<h2>Hey! am i visible😊</h2>
</div>
</div>
);
}
export default App;
And in the App.css add the below code:
.display-block {
display: block;
}
.display-none {
display: none;
}
Now run the application with the npm start command, you can see the text, button, and header are rendered on the page. To toggle the text, click on the button, and you can see it on the page.

React conditional rendering and operator
Here we will see how to conditional render using AND operator.
To conditionally render an element, use the logical && operator. Only if the condition evaluates to true in this case is an element rendered; else, it is ignored.
For example, we have a list of unread messages, so we will create a condition that will check the number of unread messages, and also it will render the number of unread messages on the page if the condition is true.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App outboxMessages={messages} />
</React.StrictMode>
);
The App.js file contains the below code:
import './App.css';
function App(props) {
const outboxMessages = props.outboxMessages;
return (
<div className='App'>
<h1>Hello!</h1>
{outboxMessages.length > 0 &&
<h2>
You have {outboxMessages.length} unread messages.
</h2>
}
<h3> The outbox message are:</h3>
<ul>
<li>{outboxMessages[0]}</li>
<li>{outboxMessages[1]}</li>
<li>{outboxMessages[2]}</li>
</ul>
</div>
);
}
export default App;
Now run the application and you can see the message is rendered on the page because the length is not less than 0.

React conditional rendering empty array
Here we will see how to conditional rendering an empty array in React.
For example, we will create an employee list, and we will check whether the list is empty or not. For this we will use the length property to check the length of the object available in the list, if it is less than 0 then it will return an empty list, otherwise, it will return the list.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import './App.css';
import React from 'react';
import List from './List';
const employee= [{ id: '3', firstName: 'Rocky', lastName: 'Vinsen' },
{ id: '4', firstName: 'Jay', lastName: 'Shetty' },]
function App() {
return (
<div className='App'>
<h1>List of employee</h1>
<List list={employee} />
</div>
);
}
export default App;
Next, list.js contains the below code:
import React from 'react';
import Item from './Item';
function List({ list }) {
if (list.length > 0) {
return (
<ul>
{list.map(item => (
<Item key={item.id} item={item} />
))}
</ul>
);
} else{
return <h3>Empty list</h3>
}
}
export default List;
The item.js component contains the below code:
import React from 'react';
function Item({ item }) {
return (
<li>
{item.firstName} {item.lastName}
</li>
);
}
export default Item;
Now run the application with the npm start command and you can see the list of employee name are rendered on the page, as the array is not empty.

Now set the array as empty in the App component, you can see the message render ‘Empty list’.

React avoid conditional rendering
Here we will see how to avoid conditional rendering with null in React js.
There is no need to present an empty, separate element as a placeholder since you can make a component’s render method return null if you want to hide it. However, when returning null, it’s vital to remember that even though the component isn’t visible, its lifecycle functions are still called.
For example, we will implement the counter with two components by following this:
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import './App.css';
import Figure from './Figure';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 }
}
onClick(e) {
this.setState(priorState => ({
count: priorState.count + 1
}));
}
render() {
return (
<div className='App'>
<Figure number={this.state.count} />
<button onClick={this.onClick.bind(this)}>Count</button>
</div>
)
}
}
export default App;
The Figure.js file contains the below code:
import React from 'react';
class Figure extends React.Component {
constructor(props) {
super(props);
}
componentDidUpdate() {
console.log('componentDidUpdate');
}
render() {
if(this.props.number % 2 === 0) {
return (
<div>
<h1>{this.props.number}</h1>
</div>
);
} else {
return null;
}
}
}
export default Figure;
Now run the application with the npm start command and you can see the Figure component only render the even values, else return null. However, if you look at the console, you’ll notice that componentDidUpdate is always called regardless of the result that renders returns.

Conditional rendering react button
Here we will see how to create a switch button using conditional rendering in React js.
For example, we will create a button that will toggle based on the condition.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import './App.css';
import React, { useState } from "react";
function App() {
let [changeText, setChangeText] = useState(true);
const onChange = () => {
return setChangeText(!changeText);
};
return (
<div className="App">
<h3>{changeText ? "Welcome" : "Farewell"} </h3>
<button onClick={() => onChange()}>click me</button>
</div>
);
}
export default App;
Now run the application with the npm start command, and you can see the button and text are rendered on the page, then click on the button you can see the text is changed Welcome to Farewell.

Conditional rendering react radio button
Here we will see how to conditionally render the radio button using React JS.
An example of a form that serves as a functional component is seen below. It has three radio buttons that indicate Male, Female, and other.
We may maintain the data in the state of the component by using useState. There are three possible genders in our situation: male, female, or other. SetGender modifies a component’s state to reflect the value of the selected radio button when the onChange event happens.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
const App = props => {
const [gender, setGender] = useState();
const handleCheck = e => {
const target = e.target;
if (target.checked) {
setGender(target.value);
}
};
const handleSubmit = e => {
e.preventDefault();
console.log(gender);
};
return (
<form onSubmit={handleSubmit} className= "App">
<div>
<h2>Gender: {gender}</h2>
<label>
<input type="radio" value="male" checked={gender === 'male'} onChange={handleCheck} />
<span>Male</span>
</label>
<label>
<input type="radio" value="female" checked={gender === 'female'} onChange={handleCheck} />
<span>Female</span>
</label>
<label>
<input type="radio" value="other" checked={gender === 'other'} onChange={handleCheck} />
<span>Other</span>
</label>
</div>
<button type="submit">Submit</button>
</form>
);
}
export default App;
Now run the application with the npm start command and you can see the paragraph, radio button, and submit button rendered on the page. When we checked the radio button and click on the submit, the selected option was rendered on the console log.

React conditional rendering based on screen size
Here we will see how to conditionally render the item on screen size in React js.
In React, there are occasions when we wish to conditionally render certain objects based on viewport size.
So we’ll look at how to use React to conditionally render things based on the size of the viewport.
React allows us to listen to the resize event released by the window in order to conditionally render elements based on viewport size.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React, { useState, useEffect } from "react";
function App() {
const [isDesktopSize, setDesktopSize] = useState(window.innerWidth > 550);
const updateMedia = () => {
setDesktopSize(window.innerWidth > 550);
};
useEffect(() => {
window.addEventListener("resize", updateMedia);
return () => window.removeEventListener("resize", updateMedia);
});
return (
<div className='App'>
{isDesktopSize ? (
<div> <h3>I show on 551px or higher</h3></div>
) : (
<div><h3>I show on 550px or lower</h3></div>
)}
</div>
);
}
export default App;
Now run the application with the npm start command and you can see the paragraph render on the page based on the screen size

Conditional rendering react two conditions
Here we will see how to do conditional rendering with react two conditions.
We check the condition if the user is equal to 1, then ‘you are Admin’ render on the page, user is equal to 2, then ‘you are manager’ else user equal to 3, then ‘ you are team lead’.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React from 'react';
function App() {
const userKind = 3;
return (
<div className="App">
<h1>Designation is:</h1>
{(() => {
if (userKind === 1) {
return (
<div>You are a Admin.</div>
)
} else if (userKind === 2) {
return (
<div>You are a Manager.</div>
)
} else if (userKind === 3) {
return (
<div>You are a Team Lead.</div>
)
}
else {
return (
<div>You are a User.</div>
)
}
})()}
</div>
);
}
export default App
Now run the application with the npm start command, and you can see the user kind is equal to 3 so it renders’ you are Team Lead’.

React conditional rendering displays 0
Here we will see why 0 is rendered while using the && operator with arr. length.
The other day, as I was writing JavaScript and React code, I ran into an amazing problem.
As I had a list of items in an array. If there were items in the array, I wanted to display a string informing the user that there were items. I didn’t want to render anything if the array contained no items.
So I used conditional rendering in React by using the logical AND (&&) operator. In my thinking, if the array was empty, nothing would be presented on the screen because the length of the array would be 0, which is a false number.
{todoList.length && You have {todoList.length} Tasks to do}
When the list of objects was empty, though, I noticed a 0 appear on the screen.
Now, we’ll look at why this happened by learning how JavaScript’s logical AND (&&) operator works and how to use it to conditionally render a component in React.
Let’s see the problem with an example, then we will see how to fix it.
import React from 'react';
function App() {
const todo = [];
return (
<div className="App">
<div>{todo.length && "There are task left"}</div>
</div>
);
}
export default App;
As the above array does not contains items, so it will render 0 on the page like below

Reason for this issue
To conditionally render the string in this example, we use JavaScript’s logical AND (&&) operator. Let’s look at how this operation works to figure out why we see a 0.
For a set of operands, the logical AND (&&) operator (logical conjunction) is true if and only if all of its operands are true. It’s most commonly used with Boolean (logical) values. It returns a Boolean value if it is. However, because the && operator returns the value of one of the given operands, it will produce a non-Boolean value if used with non-Boolean values.
It basically works by converting the first expression to true and returning the second expression. If items.length is 3, for example, the string There are items will be returned. This is due to the fact that 3 is a true value.
The solution for this is:
Simply make the first expression always return a Boolean value to address this problem. The > operator can be used to do this. So the code can be:
{todoList.length > 0 && You have {todoList.length} Tasks to do}
When the items array is empty, we return false by using items.length > 0.
The (!!) operator can also be used to convert the initial expression to a Boolean value.
{!!todoList.length && "There are items"}
As we all know, if an expression can be transformed to true, the logical NOT (!) operator will return false; otherwise, it will return true. If an expression can be transformed to true, it will return true by using the two (!!) symbols; otherwise, it will return false.
If items.length === 0, !items.length will be evaluated as true, and thus, !!items.length will be evaluated as false.
So the solution code for the above problem is:
import React from 'react';
function App() {
const todo = [];
return (
<div className="App">
<div>{todo.length >0 && "There are task left"}</div>
</div>
);
}
export default App;
React conditional rendering enum
Here we will see how to conditionally render multiple conditions with enum in React Js.
In React Js, there are numerous methods for rendering components conditionally, such as if-else, ternary operator, and so on. Developers can utilize the if-else or switch case approach if just two or three components are available to render conditionally.
If there are more than three components to render conditionally, if-else becomes complicated. As a result, developers should use an enum to keep their code clean.
For example, so first we will create two components i.e Welcome.js and Farewell.js. Then in the App.js component, we will first create enum object ‘enumObj’.
Following that, we’ll create an ‘enum’ method to render components based on their state value. Finally, we will modify the ‘App’ component and invoke the ‘enum’ function within the component to render it conditionally.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import './App.css';
import React, { Component } from 'react';
import Farewell from './Farewell';
import Welcome from './Welcome';
// Creating enum object
const Enumobj = {
welcome: <Welcome />,
farewell: <Farewell />
};
// Creating enum function to return
particular component according to state value
function Enum({ state }) {
return <div>{Enumobj[state]}</div>;
}
// we will call enum function inside the App component
class App extends Component {
render() {
return (
<div className='App'>
<Enum state="welcome"></Enum>
</div>
);
}
}
export default App;
The Welcome component contains the below code:
import React, { Component } from 'react';
// Some basic code to render first component
class Welcome extends Component {
render() {
return (
<div>
<h1 style={{color: "sky blue"}}> Welcome to the React world</h1>
<h2>hey i am the Welcome component😊</h2>
</div>
);
}
}
export default Welcome;
The Farewell component contains the below code:
import React, { Component } from 'react';
// Some basic code to render first component
class Farewell extends Component {
render() {
return (
<div>
<h1 style={{color: "sky blue"}}> Farewell from react world with lots of knowledge</h1>
<h2>hey i am the Farewell component😒</h2>
</div>
);
}
}
export default Farewell;
Now run the application with the npm start command, and you can see the Welcome component render on the page.

Conditional rendering reacts to multiple elements
Here we will see how to conditionally render multiple components in React js.
To conditionally render several elements in React, use a ternary operator. When returning multiple sibling elements, make sure to encapsulate them in a React fragment.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import './App.css';
import React from 'react';
export default function App() {
const str = 'happy';
return (
<div className='App'>
{str.length> 2 ? (
<React.Fragment>
<h2>Hii</h2>
<h2>This is React</h2>
</React.Fragment>
) : <h3>"String is missing"</h3>}
</div>
);
}
Now run the application with the npm start command and you can see the Hii, This is react render on the page.

React conditional rendering for loop
Here we will see how to conditional render for loop in React js.
As we know, we can perform practically whatever a for loop does by using Map in React js.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React from 'react'
import './App.css';
const App = ()=> {
const animals = ["Dog", "Bird", "Cat", "Mouse", "Horse"];
return (
<ul className='App'>
{animals.length>0? animals.map(animal=>(<li>{animal}</li>)): "No animals left"}
</ul>
);
};
export default App;
Now run the application with the npm start command and you can see the list of animals are rendered on the page.

Conditional rendering react-router
Here we will see how to conditional render with react-router in React js.
What is React -router?
React Router is a standard library for React routing. It allows navigating between views of different components in a React Application, changes the browser URL, and keeps the UI in sync with the URL.
To use the React router, we need to install the React router, with the below command:
npm install react-router-dom@6
Once we install we will import the library into the React component.
import {
BrowserRouter as Router,
Routes,
Route,
Link
} from 'react-router-dom';
In the above statement, the main component react-router are:
- Browser router: BrowserRouter is a router implementation that keeps your UI in sync with the URL by utilizing the HTML5 history API (pushState, replaceState, and the popstate event). All of the other components are stored in the parent component.
- Routes: It is a new component added in v6 as well as an upgrade to the component. The following are the primary advantages of Routes versus Switches:
- s and relative s
- Instead of being travelled in order, routes are determined depending on the best match.
- Route: The route is a conditionally displayed component that displays some UI when its path matches the current URL.
- Link: The link component is used to create links to multiple routes and to provide application navigation. It functions similarly to the HTML anchor tag.
Now we will see an example where we will create home , about, contact and logout pages. Then we will wrap all the content of your page inside the return function inside the router . Create the induvial routes inside the component next. As an example, suppose we wish to render a component only if a state is true, such as if a user is logged in, otherwise please logged in will render i.e. logout component.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React, { Component } from 'react';
import { BrowserRouter as Router, Routes, Route, Link, Navigate } from 'react-router-dom';
import Home from './Home';
import Contact from './Contact';
import About from './About';
import Logout from './Logout';
import './App.css';
const LoggedIn = false;
class App extends Component {
render() {
return (
<Router>
<div className='App'>
<ul>
<li>
<Link to="/">Home🏠</Link>
</li>
<li>
<Link to="/about">About Us👀</Link>
</li>
<li>
<Link to="/contact">Contact Us📞</Link>
</li>
</ul>
<Routes>
{/* // if LoggedIn is true then it will render Home page else it will render logout. */}
<Route exact path='/' element={LoggedIn ? (<Home />) : (<Navigate replace to={"/logout"} />
)}></Route>
<Route exact path='/about' element={<About />}></Route>
<Route exact path='/logout' element={<Logout />}></Route>
<Route exact path='/contact' element={<Contact />}></Route>
</Routes>
</div>
</Router>
);
}
}
export default App;
The home component contains the below code:
import React from 'react';
function Home (){
return <h1>Welcome to SPGuides</h1>
}
export default Home;
The contact component contains the below code:
import React from 'react'
class Contact extends React.Component {
render() {
return <h1>Contact : +09876543000000</h1>
}
}
export default Contact
The about component contains the below code:
import React from 'react';
function About (){
return <h1>We create tons of free Office 365, SharePoint, PowerApps, Power Automate, Power BI, SPFx etc videos.
At least weekly we upload 2 videos.</h1>
}
export default About;
The Logout.js component contains the below code:
import React from 'react'
class Logout extends React.Component {
render() {
return <h1>Please Login🗝</h1>
}
}
export default Logout
Now run the application with npm start command, and you can see the isLoggedIn = false, so it will show you ‘Please Login 🗝’, and if you click on the Home page.

Now set the isLoggedIn = true, and now if you click on the Home page, you can navigate into the Home page.

React conditional rendering fade out
Here we will see how to conditional render fade in/ fade out effect in React js.
Conditional rendering in React operates similarly to JavaScript conditions. And, based on the if/else statement, React will efficiently deal with DOM objects and decide whether to hide or show elements. As a result of conditional rendering in react, your DOM object will not contain unneeded and undesirable elements, improving the smooth running of your code, debugging, and design.
Now we will see two different approaches to conditionally render fade in/ fade out effect in react js.
Method 1- Using onAnimatedEnd Event
React includes some built-in event handlers for catching and handling events during the capture phase. Native events such as preventDefault() and stopPropagation() can be used by React components…
In our scenario, we want to capture the animation transition when we wish to unmount our component and have more control over this phase. This is possible with:
onAnimationEnd — This event is triggered when the animation has finished.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React,{useState} from "react";
import './App.css';
const mountedStyle = { animation: "inAnimation 250ms ease-in" };
const unmountedStyle = {
animation: "outAnimation 270ms ease-out",
animationFillMode: "forwards"
};
export default function App() {
const [isMounted, setIsMounted] = useState(false);
const [displayDiv, setDisplayDiv] = useState(false);
return (
<div className="App">
<button onClick={() => {
setIsMounted(!isMounted)
if (!displayDiv) setDisplayDiv(true); //We should Render our Div
}
}>Hide/Show</button>
{ //Conditional Rendering
displayDiv && <div
className="transitionDiv"
style={isMounted ? mountedStyle : unmountedStyle}
onAnimationEnd={() => { if (!isMounted) setDisplayDiv(false) }}
></div>}
</div>
);
}
The App.css contains the below code
.transitionDiv {
background: rgb(181, 151, 40);
height: 100px;
width: 200px;
margin: 0 auto;
}
@keyframes inAnimation {
0% {
opacity: 0;
visibility: hidden;
}
100% {
opacity: 1;
visibility: visible;
}
}
@keyframes outAnimation {
0% {
opacity: 1;
}
100% {
opacity: 0;
visibility: hidden;
}
}
Now run the application with the npm start command and you can see the button is rendered on the page. By clicking on the button we can Fade in and Fade out of the element.
As we can see, when the animation ends, the value changes to false. The onAnimationEnd Event trigger is appreciable.
We also add a new variable called isMounted, which shows if a button marked “Show/Hide” was clicked by the user.

Method 2- Simple custom hook
Here we will create a simple function in UseDelayMount.js component that will postpone the unmount stage and let the transition to complete before React removes our element from the DOM Object
This function will postpone our variable showDiv before changing its value to false.
In this function, We establish a new variable isMounted, which indicates if our user clicked the button (Show/Hide). Based on that, useDelayUnmount will give ShowDiv a certain amount of time before adjusting its value, allowing our animation to effect the Div element before removing it from the DOM.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React, { useState } from "react";
import useDelayUnmount from './UseDelayMount';
const mountedStyle = { animation: "inAnimation 250ms ease-in" };
const unmountedStyle = {
animation: "outAnimation 270ms ease-out",
animationFillMode: "forwards"
};
export default function App() {
const [isMounted, setIsMounted] = useState(false);
const displayDiv = useDelayUnmount(isMounted,250);
return (
<div className="App">
<button onClick={() => setIsMounted(!isMounted)}>Show/Hide</button>
{/* //Conditional Rendering */}
{ displayDiv &&
<div
className="transitionDiv"
style={isMounted ? mountedStyle : unmountedStyle}
></div>
}
</div>
);
}
The userDelayMount.js contains the below code:
import React,{useState, useEffect} from "react";
export default function useDelayUnmount(isMounted, delayTime) {
const [displayDiv, setDisplayDiv] = useState(false);
useEffect(() => {
let timeoutId;
if (isMounted && !displayDiv) {
setDisplayDiv(true);
} else if (!isMounted && displayDiv) {
timeoutId = setTimeout(() => setDisplayDiv(false), delayTime); //delay our unmount
}
return () => clearTimeout(timeoutId); // cleanup mechanism for effects , the use of setTimeout generate a sideEffect
}, [isMounted, delayTime, displayDiv]);
return displayDiv;
}
Now run the application, with the npm start command and you can see the show/ hide button rendered on the page, by clicking on this you can fade in and fade out the element.

Conditional rendering react props
Here we will see how to conditionally render react props.
For example, we will create three components, and it will render the component based on the condition.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React from "react";
import './App.css';
const Message = (props) => {
return <h1>Welcome to the React js</h1>;
}
const Message2 = (props) => {
return <h2>Learn and grow with react</h2>;
}
const Content = (props) => {
return <p>React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
It lets you compose complex UIs from small and isolated pieces of code called “components</p>;
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {isSwitchOn: true};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isSwitchOn: !prevState.isSwitchOn
}));
}
render() {
if(this.state.isSwitchOn) {
return (
<div>
<Message />
<Message2 />
<Content />
<button onClick={this.handleClick}>
{ this.state.isSwitchOn ? 'ON' : 'OFF' }
</button>
</div>
);
} else {
return (
<div>
<Message />
<Content />
<button onClick={this.handleClick}>
{ this.state.isSwitchOn ? 'ON' : 'OFF' }
</button>
</div>
);
}
}
}
export default App
Now run the application with the npm start command and you can see Message 1, Message 2, content, and button get rendered on the page. By clicking on the button we can toggle between the

React conditional rendering props.children
Here we will see how to conditionally render props.children in React.
For example, we have two components, the My component, and the App component. So, here App component contains the child props, it will render if isActive is 1 else it will render No result found.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React from 'react';
function MyComponent(props) {
return (
<div>
{props.isActive ? (props.children)
: (<><h1>No Data Found</h1></>)}
</div>
);
}
class App extends React.Component {
render() {
return (
<MyComponent isActive={1}>
<div>
<h1>React Tutorials</h1>
<p>Let us learn React</p>
<ul>
<li>React Js</li>
<li>React Native</li>
</ul>
</div>
</MyComponent>
);
}
}
export default App;
Now run the application with the npm start command and you can children elements are rendered on the page.

React conditional rendering parent
Here we will how to conditionally render the child component in the parent component.
For example, we will see how to create a React application with an App component as a parent component that will conditionally re-render the Form component and refresh the UI.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const messages = ['Hi i have something for you', 'whats up', 'lets work together'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The App.js file contains the below code:
import React, { useState } from 'react';
import './App.css';
const App = () => {
const [isSignin, setIsSignin] = useState(false);
return (
<div className='App'>
<div>Username: Spguides</div>
<div onClick={() => setIsSignin((prev) => !prev)}>
{isSignin ? <Form Signin /> : <Form Signout />}
</div>
</div>
);
};
const Form = ({ Signin, Signout }) => {
return (
<div>
{Signin ? (
<>
<input type='text' placeholder="Email" />
<input type='password' placeholder="Password" />
<button>Login</button>
</>
) : null}
{Signout ? (
<button>Logout</button>
) : null}
</div>
);
};
export default App;
Now run the application with the npm start command and you can see the Logout button render on the page, as the passed value is false, and username.
Once you click on the Logout button, the Login form with the button will render on the page.

Conclusion
This React js tutorial illustrates conditional rendering in React js, like how to conditional render in class and functional components in react js, and also we saw how to conditionally render in react js with different types of examples. These are listed below:
- What is conditional rendering in React
- How to do conditional rendering in react class component
- How to do conditional rendering in react functional component
- Conditional rendering react hooks
- Conditional rendering react ternary
- How to do conditional rendering array in React
- Conditionally render attribute react
- React conditional rendering vs display none
- React conditional rendering and operator
- React conditional rendering empty array
- React avoid conditional rendering
- conditional rendering react button
- conditional rendering react radio button
- react conditional rendering based on screen size
- conditional rendering react two conditions
- react conditional rendering displays 0
- react conditional rendering enum
- conditional rendering react multiple elements
- react conditional rendering for loop
- conditional rendering react router
- react conditional rendering based on URL
- react conditional rendering fade out
- conditional rendering react props
- react conditional rendering props.children
- react conditional rendering parent
- react conditional rendering breakpoint
I am Bijay a Microsoft MVP (8 times – My MVP Profile) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com