Database examples

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.

function Dashboard(props) {
const { isLoggedIn } = props
if(isLoggedIn){
return
} else{
return
}
}

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.

Rewrite the above function as follows:

function Dashboard(props) {
const { isLoggedIn } = props
return (
<>
{isLogged?)

)
}

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.

function LoginBtn(props) {
return (

);
}
function LogoutBtn(props) {
return (

);
}
function Dashboard() {
const [loggedIn, setLoggedIn] = useState(true)
const handleLogin = () => {
setLoggedIn(true)
}
const handleLogout = () => {
setLoggedIn(false)
}
let button;
if (loggedIn) {
button =
} else {
button =
}
return (
<>
{loggedIn}

)
}


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.

function ShowNotifications(props) {
const { notifications } = props
return (
<>
{notifications.length > 0 &&


You have {notifications.length} notifications.


}

)
}

Then, to render an element if the logical expression && evaluates to false, chain the || operator logic.

The following function displays the message “You have no notification” if no notification is transmitted as props.

function ShowNotifications(props) {
const { notifications } = props
return (
<>
{notifications.length > 0 &&


You have {notifications.length} notifications.

||

You have no notifications


}

)
}

Prevent a component from displaying

To hide a component even if it was rendered by another component, return null instead of its output.

Consider the following component which only displays a warning button if a warning message is passed as props.

function Warning (props) {
const {warningMessage} = props
if (!warningMessage) {
return null
}
return (
<>


)
}

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.


learn-react-featured
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