Design+Code logo

Quick links

Suggested search

CodeSandbox link

You can find the full code for this tutorial at https://codesandbox.io/s/conditional-rendering-dpvzy.

Logical AND operator

The logical AND (&&) operator can be used to render different UIs depending on some conditions. Let's say we want to display a message saying You have 1 new notification only when the user has one notification or more.

Let's create our NotificationCard component. It'll simply be a text that will depend on the local state. Learn about useState in the useState Hook section of this handbook.

import React, { useState } from "react";

const NotificationCard = () => {
    const [notificationNumber, setNotificationNumber] = useState(1)

    return (
        <div>
            <p>You have {notificationNumber} new notification</p>
        </div>
    );
};

export default NotificationCard;

Then, we'll add a condition using the logical AND (&&) operator to only display the text when the notificationNumber is greater or equal to 1.

<Wrapper>
    {notificationNumber >= 1 &&
        <Paragraph>You have {notificationNumber} new notification</Paragraph>
		}
</Wrapper>

You can change the initial value of notificationNumber to 0 and the text will disappear.

const [notificationNumber, setNotificationNumber] = useState(0)

Screen Shot 2021-02-25 at 11.49.20 AM

You can style your components by using the styled-components package in your project. Learn more about it in the Styling in React section of this handbook.

The final code for the NotificationCard with styling is:

import React, { useState } from "react";
import styled from "styled-components";

const NotificationCard = () => {
    const [notificationNumber, setNotificationNumber] = useState(1);

    return (
        <Wrapper>
            {notificationNumber >= 1 && (
                <Paragraph>You have {notificationNumber} new notification</Paragraph>
            )}
        </Wrapper>
    );
};

export default NotificationCard;

const Wrapper = styled.div`
    background: rgba(255, 255, 255, 0.6);
    box-shadow: inset 0 0 0 0.5px rgba(255, 255, 255, 0.6);
    border-radius: 30px;
    padding: 20px;
    width: 300px;
    display: grid;
    gap: 30px;
    justify-items: center;
    align-items: center;
`;

const Paragraph = styled.p`
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
    font-style: normal;
    font-size: 15px;
    line-height: 48px;
    text-align: center;
`;

If...else statement

With an if...else statement, we can specify a condition and then, do something depending on whether that condition is true or false. In the example below, we're showing the logout button depending on the value of isLoggedIn. If the user is logged out, we want to display the Login text. If the user is logged in, we want to display the Logout text. I'm using the useState hook to set the state.

import React, { useState } from "react";

const SignInButton = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(true);

    if (isLoggedIn) {
        return <button>Logout</button>;
    } else {
        // If user is logged out
        return <button>Login</button>;
    }
};

export default SignInButton;

You can change the also initial value of isLoggedIn to false and the text will change to Login.

const [isLoggedIn, setIsLoggedIn] = useState(false)

Screen Shot 2021-03-16 at 4.35.00 PM

You can style your components by using the styled-components package in your project. Learn more about it in the Styling in React section of this handbook.

The final code for the SignInButton with styling and using the if...else statement is:

import React, { useState } from "react";
import styled from "styled-components";

const SignInButton = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(true);

    if (isLoggedIn) {
        return <Button>Logout</Button>;
    } else {
        // If user is logged out
        return <Button>Login</Button>;
    }
};

export default SignInButton;

const Button = styled.div`
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
    font-weight: bold;
    background: linear-gradient(91.4deg, #2fb8ff 0%, #9eecd9 100%);
    border: none;
    border-radius: 30px;
    box-shadow: 0px 20px 40px rgba(147, 231, 221, 0.3);
    cursor: pointer;
    display: grid;
    text-align: center;
    padding: 12px 0;
    width: 100%;
    position: relative;
    justify-content: center;
    max-width: 300px;
    margin: 0 auto;
    transition: 0.8s cubic-bezier(0.075, 0.82, 0.165, 1);
    color: white;
    font-style: normal;
    font-weight: normal;
    font-size: 17px;
    line-height: 130%;

    :hover {
        transform: translateY(-2px);
        box-shadow: 0px 20px 40px rgba(0, 0, 0, 0.15),
        inset 0 0 0 0.5px rgba(0, 0, 0, 0.3), inset 0 10px 40px rgba(0, 0, 0, 0.1);
    }

    :focus {
        outline: none;
    }
`;

Using ternary operators

An alternative to using an if...else statement is the ternary operator. This operator takes in three operands and is one of the most succinct ways to render something conditionally in React. We'll use the same example as above but use the ternary operator instead of the if...else statement.

const SignInButton = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(true);

    return (
        <div>
            {isLoggedIn ? <button>Logout</button> : <button>Login</button>}
        </div>
        );
}

export default SignInButton

The result is exactly the same as the if...else statement, except that the code is cleaner and more readable.

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Props

READ NEXT

Load Local Data

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Videos

ePub

Assets

Subtitles

1

Intro to React Hooks

An overview of React Hooks and the frameworks you can use to build your React application blazingly fast

3:39

2

Create your first React app

Create your first React project from the Terminal and save it on your local computer

4:23

3

React Component

Create your first JSX component using React

2:54

4

Styling in React

How to style your React components using inline styling, separate stylesheets or styled-components

5:06

5

Styles and Props

Render different styles depending on different properties passed to your component

2:22

6

Understanding Hooks

Learn about the basics of React Hooks, which introduced at React Conf 2018

3:21

7

useState Hook

Use the useState hook to manage local state in your React component

2:54

8

useEffect Hook

Manage with your component's lifecycle with the useEffect hook

3:41

9

useRef Hook

Learn about the useRef hook, which replaces the JavaScript getElementById way

3:00

10

Props

Learn about props in React to pass data from parent to child components

3:11

11

Conditional Rendering

Render different UIs depending on different conditions and states

4:21

12

Load Local Data

Load local JSON data into your React application

4:04

13

Fetch Data from an API

Learn the basics of asynchronous functions and promises by fetching data from an API using fetch, useEffect and useState

5:40

14

Toggle a state

Learn how to toggle a state from true to false and back again

4:05

15

useInput Hook

Create a hook to get the value and the onChange event of input fields

6:04

16

Gatsby and React

Create a static content-oriented website using React on Gatsby

6:44

17

NextJS and React

Create your first NextJS React application

5:24

18

React TypeScript Part 1

Learn how to create a React TypeScript application using the Create React App, Gatsby and NextJS methods

8:19

19

React TypeScript Part 2

Learn the basics of TypeScript and how to use TypeScript in a React component

7:35

20

useScrollPosition Hook

Create a custom hook to listen to the current window position of the user

4:26

21

useOnScreen hook

Create a custom hook to listen to when an element is visible on screen

8:08

22

useContext Hook

Manage global states throughout the entire application

8:32

23

Fragments

Group multiple children together with React Fragments

2:43

24

Lazy Loading

Lazy Load heavy components to improve performance

4:05

25

React Suspense

Wait for data with React Suspense and React.lazy

3:13

26

Environment Variables

Make environment variables secret with a .env file

4:43

27

Reach Router

Create a multiple-pages React application with Reach Router

5:31

28

URL Params

Create unique URL with URL Params

4:04

29

SEO and Metadata

Optimize a React application for search engines with React Helmet

6:47

30

Favicon

Add an icon to a React website

3:03

31

Dynamic Favicon

Change the favicon's fill color depending on the user's system appearance

2:14

32

PropTypes

Implement props type-checking with PropTypes

3:54

33

Custom PropTypes

Create a custom PropType using a validator function

3:58

34

useMemo Hook

Prevent unnecessary re-renders when the component stays the same

4:05

35

forwardRef Hook

Forward a ref to a child component

3:28

36

Handling Events

How to handle events in React

5:44

37

Spread attributes

Learn how to make use of the spread operator

3:35

38

useMousePosition Hook

Detect the user's mouse position on a bound element

4:55

39

useReducer with useContext Part 1

Create a reducer to be used in a context

7:33

40

useReducer with useContext Part 2

Incorporate useReducer with useContext

6:48

41

useReducer with useContext Part 3

Connect the context and reducer with the frontend

5:43

42

Netlify

Deploy to production using Netlify

5:08

43

Gatsby Cloud

Deploy to production using Gatsby Cloud

6:19

44

Gatsby Plugin Image

Use gatsby-plugin-image for automatic image resizing, formatting, and higher performance

8:11

45

useOnClickOutside Hook

Toggle a modal visibility with a useOnClickOutside hook

6:32

46

useWindowSize Hook

Create a hook to determine the width and height of the window

4:14

47

usePageBottom hook

Detect if the user scrolled to the bottom of the page

4:48

48

useLocalStorage Hook

Store an item in a browser's local storage

5:27

49

Three.js in React Part 1

Bring your website to life with beautiful 3D objects

17:33

50

Three.js in React Part 2

Bring your website to life with beautiful 3D objects

11:18