Design Converter
Education
Developer Advocate
Last updated on Nov 1, 2023
Last updated on Aug 9, 2023
Conditional rendering in React is a powerful tool that lets us dynamically alter our application's UI based on the state of the components. It's like a traffic light for our components, controlling what gets rendered and when.
We'll start by understanding the basics of conditional rendering, and then we'll dive into more complex scenarios where we will conditionally render content based on multiple conditions. We'll also discuss various techniques to implement conditional rendering in React, such as using ternary operators, switch statements, and even immediately invoked function expressions (IIFEs).
This post is for experienced developers who have a decent understanding of React but want to delve deeper into conditional rendering. So, buckle up, and let's get started!
Mastering conditional rendering in React will not only make your code cleaner and easier to understand but also optimize your app's performance by avoiding unnecessary rendering.
Stay tuned, as we're about to dive deep into the world of React conditional rendering. It's going to be a fun ride!
In the simplest terms, conditional rendering is a way to render different user interface (UI) elements in a React component based on certain conditions. It's like an if-else statement for your UI, helping you control what your users see and when they see it.
When a component's state changes, React runs the render method of that component again. This is where conditional rendering comes into play. If the new state fulfills certain conditions, we can control what gets rendered.
1 import React from 'react'; 2 function App() { 3 const [isLoggedIn, setIsLoggedIn] = React.useState(false); 4 return ( 5 <div> 6 {isLoggedIn ? ( 7 <h1>Welcome back, user!</h1> 8 ) : ( 9 <h1>Please log in.</h1> 10 )} 11 </div> 12 ); 13 } 14 export default App; 15
In the above code, we're using a ternary operator to conditionally render a welcome message if the user is logged in (i.e., if isLoggedIn is true). If isLoggedIn is false, we render a login prompt instead.
Let's look at some common ways to implement conditional rendering in React:
The ternary operator is a JavaScript operator that takes three operands: a condition, an expression to execute if the condition is true, and another expression to execute if the condition is false.
1 import React from 'react'; 2 3 function App() { 4 const [isLoading, setIsLoading] = React.useState(true); 5 6 return ( 7 <div> 8 {isLoading ? ( 9 <h1>Loading...</h1> 10 ) : ( 11 <h1>Content loaded!</h1> 12 )} 13 </div> 14 ); 15 } 16 17 export default App; 18
In this example, we're using a ternary operator to show a loading state if isLoading is true. If isLoading is false, we show that the content has loaded.
As you continue to master the art of conditional rendering in React and other front-end technologies, you might find yourself seeking tools that can make your learning and development journey even smoother. That's where WiseGPT comes in.
WiseGPT is a state-of-the-art AI tool designed to assist developers like you in writing code, understanding complex concepts, and even generating blog posts or documentation. It's like having a seasoned developer by your side, ready to assist you 24/7.
With WiseGPT, you can generate code snippets, ask for explanations of complicated programming topics, and even brainstorm ideas for your next project. It's not just about providing answers—it's about helping you understand the 'why' and 'how' behind those answers.
The best part? WiseGPT learns from your interactions, becoming more personalized and effective the more you use it. So Sign up for WiseGPT today and supercharge your development journey with the power of AI!
Short circuit evaluation in JavaScript uses the logical AND (&&) operator. If the left-hand expression is true, the right-hand expression is returned. If the left-hand expression is false, React will skip the right-hand expression and return null.
1 import React from 'react'; 2 3 function App() { 4 const [error, setError] = React.useState(null); 5 6 return ( 7 <div> 8 {error && <h1>An error occurred: {error}</h1>} 9 </div> 10 ); 11 } 12 13 export default App; 14
In this code snippet, if error is not null, React will render an error message. Otherwise, it will render nothing.
The logical OR (||) operator can also be used for conditional rendering in React. If the left-hand expression is false, the right-hand expression is returned.
1 import React from 'react'; 2 3 function App() { 4 const [name, setName] = React.useState(''); 5 6 return ( 7 <div> 8 <h1>{name || 'Guest'}</h1> 9 </div> 10 ); 11 } 12 13 export default App; 14
In the above code, if name is not an empty string, it will be rendered. Otherwise, 'Guest' will be rendered.
While you can't use if-else statements directly inside the JSX, you can use them inside the render method or functional component before the return statement.
1 import React from 'react'; 2 3 function App() { 4 const [isLoggedIn, setIsLoggedIn] = React.useState(false); 5 let message; 6 7 if (isLoggedIn) { 8 message = <h1>Welcome back, user!</h1>; 9 } else { 10 message = <h1>Please log in.</h1>; 11 } 12 13 return ( 14 <div> 15 {message} 16 </div> 17 ); 18 } 19 20 export default App; 21
Switch statements in JavaScript can be a powerful tool for conditional rendering in React, especially when you have multiple conditions to check against. They can make your code cleaner and easier to read compared to using multiple if-else or ternary operators.
1 import React from 'react'; 2 3 function App() { 4 const [status, setStatus] = React.useState('loading'); 5 let message; 6 7 switch (status) { 8 case 'loading': 9 message = <h1>Loading...</h1>; 10 break; 11 case 'loaded': 12 message = <h1>Content loaded!</h1>; 13 break; 14 case 'error': 15 message = <h1>An error occurred!</h1>; 16 break; 17 default: 18 message = <h1>Nothing to display.</h1>; 19 } 20 21 return ( 22 <div> 23 {message} 24 </div> 25 ); 26 } 27 28 export default App; 29
In this example, we're using a switch statement to conditionally render messages based on the status state.
Immediately Invoked Function Expressions
IIFEs are another advanced technique for implementing conditional rendering in React. This approach can be particularly useful when you need to run some additional JavaScript code during the rendering process.
1 import React from 'react'; 2 3 function App() { 4 const [count, setCount] = React.useState(0); 5 6 return ( 7 <div> 8 {(() => { 9 if (count === 0) { 10 return <h1>No items.</h1>; 11 } else if (count === 1) { 12 return <h1>One item.</h1>; 13 } else { 14 return <h1>{count} items.</h1>; 15 } 16 })()} 17 </div> 18 ); 19 } 20 21 export default App; 22
In the above code snippet, we're using an IIFE to conditionally render a message based on the count state.
Element variables allow you to conditionally create and include JSX in your components. This method is useful when you want to render different components depending on the state of your application.
1 import React from 'react'; 2 3 function App() { 4 const [isLoggedIn, setIsLoggedIn] = React.useState(false); 5 let Component; 6 7 if (isLoggedIn) { 8 Component = <LoggedInComponent />; 9 } else { 10 Component = <LoggedOutComponent />; 11 } 12 13 return ( 14 <div> 15 {Component} 16 </div> 17 ); 18 } 19 20 export default App; 21
In this example, we're conditionally setting the Component variable to either the LoggedInComponent or LoggedOutComponent based on the isLoggedIn state. We then render the Component variable in our JSX.
While conditional rendering is a powerful tool, it's important to remember that it can also lead to performance issues if not used properly. React's virtual DOM diffing (reconciliation) algorithm is efficient, but unnecessary rendering can still slow down your app. Always try to minimize the number of renderings and only re-render when absolutely necessary.
In the next part, we'll explore a few examples of how to conditionally render components based on complex conditions and user interactions. We'll also discuss how to avoid unnecessary rendering and optimize your React application's performance. Stay tuned!
A common use case for conditional rendering is to render components depending on user interactions. Let's take a look at an example where we render a welcome message once the user clicks a login button.
1 import React from 'react'; 2 3 function App() { 4 const [isLoggedIn, setIsLoggedIn] = React.useState(false); 5 6 const handleLogin = () => { 7 setIsLoggedIn(true); 8 }; 9 10 return ( 11 <div> 12 {isLoggedIn ? ( 13 <h1>Welcome back, user!</h1> 14 ) : ( 15 <button onClick={handleLogin}>Log in</button> 16 )} 17 </div> 18 ); 19 } 20 21 export default App; 22
In this example, when the user clicks the login button, the isLoggedIn state is set to true, causing the component to re-render and the welcome message to appear.
Sometimes, you want to render a list of components, but only if the list isn't empty. Here's how you can do this:
1 import React from 'react'; 2 3 function App() { 4 const [todos, setTodos] = React.useState(['Buy milk', 'Walk the dog']); 5 6 return ( 7 <div> 8 {todos.length > 0 ? ( 9 <ul> 10 {todos.map((todo, index) => ( 11 <li key={index}>{todo}</li> 12 ))} 13 </ul> 14 ) : ( 15 <h1>No todos left!</h1> 16 )} 17 </div> 18 ); 19 } 20 21 export default App; 22
In this example, if the todos array has one or more items, we render a list of those items. If the todos array is empty, we render a message saying there are no todos left.
When fetching data from an API, you might want to show a loading spinner while the data is being fetched. Once the data has been fetched, you can then render the data.
1 import React, { useState, useEffect } from 'react'; 2 3 function App() { 4 const [isLoading, setIsLoading] = useState(true); 5 const [data, setData] = useState(null); 6 7 useEffect(() => { 8 fetch('https://api.example.com') 9 .then(response => response.json()) 10 .then(data => { 11 setData(data); 12 setIsLoading(false); 13 }); 14 }, []); 15 16 return ( 17 <div> 18 {isLoading ? ( 19 <h1>Loading...</h1> 20 ) : ( 21 <div>{JSON.stringify(data)}</div> 22 )} 23 </div> 24 ); 25 } 26 27 export default App; 28
In this example, while the data is being fetched from the API, we're showing a loading message. Once the data has been fetched, we render the data.
React's conditional rendering is a powerful feature that can make your components dynamic and interactive. It's an essential tool in your React toolbox, so make sure to understand it well. Whether you're using ternary operators, logical operators, switch statements, or IIFEs, the key is to choose the right tool for the job. Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.