How to Implement Conditional Rendering in React.js (With Examples)
Posted onAuthorJoanne C. KellyComments Off on How to Implement Conditional Rendering in React.js (With Examples)
Conditional rendering refers to changing the behavior of an application based on its state. For example, you can change your React app’s greeting to dark at night. This way you have a different display message depending on the time of day.
Conditional rendering allows you to render different React components or elements if a condition is met. In this tutorial, you’ll learn about the different ways to use conditional rendering in React.js applications.
Ways you can implement conditional rendering
To follow these examples, you should have a basic understanding of how React works. If you’re having trouble doing this, don’t worry, we have a helpful beginner’s guide to React.js.
Using Conditional Statements
As in JavaScript, you can use conditional statements like if…else to create elements when certain conditions are met.
For example, you can display an item specified in the if block when one condition is met and display another in other block if the condition is not met.
Consider the following example that displays a login or logout button depending on the user’s login status.
This function makes a button different depending on the is connected value passed as an accessory.
USE VIDEO OF THE DAY
Related: How to use props in ReactJS
Alternatively, you can use the ternary operator. The ternary operator takes a condition followed by the code to be executed if the condition is the truth followed by the code to execute if the condition is false.
The ternary operator makes the function cleaner and more readable compared to the operator otherwise declaration.
Declaring Element Variables
Element variables are variables that can hold JSX elements and be rendered as needed in a React application.
You can use item variables to display only a certain part of the component when your application meets the specified condition.
For example, if you want to show only a login button when the user is not logged in and a logout button only when they are logged in, you can use element variables.
In the code above, first create the components for the login and logout buttons, then define the component to render each of them under different conditions.
In this component, use the React status hook to know when the user is logged in.
Related: Master Your Reaction Skills By Learning These Extra Hooks
Now depending on the state either render the Where making up.
If the user is not logged in, display the component else render eand making up. Both handle functions change the connection state when the respective button is clicked.
Using Logical Operators
You can use logic && Operator to conditionally render an item. Here an element is rendered only if the condition evaluates to true, otherwise it is ignored.
If you want to tell a user how many notifications they have only when they receive one or more notifications, you can use the following.
Now if you pass ‘warningMessage’ to the component , a warning button will be rendered. However, if you don’t, will return null and the button will not display.
// the warning button is rendered // the warning button is not rendered
Examples of conditional rendering in real React applications
Use conditional rendering to accomplish different tasks in your application. Some of these include rendering API data only when available and displaying an error message only when an error exists.
Render data fetched from an API in React
Retrieving data from an API can take some time. Therefore, first check if it is available before using it in your application, otherwise React will throw an error if it is not available.
The following function shows how you can conditionally render data returned by an API.
function FetchData() { const [data, setData] = useState(null); const apiURL = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"; // Fetch data from API using Axios const fetchData = async () => { const response = await axios.get(apiURL) // Update state with the data setData(response.data) } return ( <>
Astronomy picture of the day
{ data &&
{data.title}
{data.explanation}
} > ) }
In the above function fetch data from NASA Apod API using Axios. When the API returns a response, update the state and use the logical operator && to display data only when it is available.
Related: How to use APIs in React using Fetch and Axios
Displaying error messages
In cases where you want to display an error only when it exists, use conditional rendering.
For example, if you are creating a form and you want to display an error message if a user has entered the wrong email format, update the state with the error message and use an if statement to give it back.
function showError() { const [error, setError] = useState(null) return ( <> { if (error) {
An error occurred: {error}
} } > ) }
Choosing what to use in your React app
In this tutorial, you learned about the different ways to conditionally render JSX elements.
All the methods discussed give the same results. Make a choice on what to use based on the use case and the level of readability you want to achieve.
7 Best Free Tutorials to Learn React and Build Web Apps
Free courses are rarely this comprehensive and useful – but we’ve found several React courses that are excellent and will get you started on the right foot.
Read more
About the Author
Marie Gathoni (6 articles published)
Mary Gathoni is a software developer with a passion for creating technical content that is not only informative but also engaging. When she’s not coding or writing, she enjoys spending time with friends and being outdoors.
More Mary Gathoni
Subscribe to our newsletter
Join our newsletter for tech tips, reviews, free ebooks and exclusive offers!
* Getty In the world of CX, the only constant is change. Priorities and customer demands are constantly changing, as is technology and the market. Successful companies continually innovate to stay ahead of the competition and deliver great, relevant experiences to customers. Here are 20 new examples of CX innovation in action: 1 . Prose […]
Business owners of all sizes and in all industries recognize the importance of the data they have in making important decisions to move their businesses forward. With master data management, companies ensure that their shared data is consistent and accurate, providing the best insights based on the quality of that data. In addition to master […]
The Boeing 737 was one of the most successful airplanes of all time. It is the most delivered commercial aircraft to date (although now overtaken in orders by the Airbus A320). The first 737-100 entered service in 1968, and the type went through several variants leading to the 737 MAX series today. The usage and […]