This is a masterclass on conditional rendering in ReactJS.
Have you ever tried to show a specific component when a user does an action in ReactJS? Obviously, you must have done it. The main reason for using conditional rendering in ReactJS is simplicity and flexibility. Moreover you can also build a custom component with certain conditions and reuse it whenever you want.
This may sound a bit theoretical to understand. So, I have added three cases to help you understand the concept of conditional rendering in React. You can use any of these approaches as per your use case. Here is the table to show you what you’ll learn ahead.
Case No | Name | Use Case | Example |
|---|---|---|---|
1 | Display a component conditionally | Display only one component or jsx | Show a Modal only when the condition is true |
2 | Toggling Between Two Components | Toggle between two components | Show a dashboard when a user is logged in, otherwise show a login screen |
3 | Multiple Component Rendering | To deal more than two components | Form steps or Quiz screens on the basis of certain case |
Why is conditional rendering in React JS important?
Conditional rendering in ReactJS involves presenting varied content depending on specific conditions or states. It enables the creation of dynamic user interfaces that can adjust to alterations in data and user interactions. You can have the following benefits using conditional rendering in React JS:
Better User Experience: It'll help you create dynamic interfaces that adapt to user actions and data changes.
Enhanced Performance: To prevent performance issues, you must avoid rendering unnecessary components in larger applications.
Streamlined Code: Using conditional statements can enhance code readability and simplicity. You can decide what content should be rendered and avoided.
Flexibility: It'll build flexible and customizable components by rendering different content based on the application state. In this, components can also adapt to various contexts and user interactions.
3 Cases of React JS Conditional Rendering
1. Displaying a Component Conditionally (Case #1):
The most basic application of conditional rendering is to display a component based on a specific condition.
When we want to display only one component or jsx, in this case, we handle conditional rendering in React using the short-circuit (&&) operator.
To achieve this, we need to have a state variable to keep track of condition, whether the component should be shown or hidden.
For example, you can show a modal only when the showResultModal state is true.
Here's a simplified example:
1import { useState } from 'react'
2import ModalWrapper from 'ui/ModalWrapper'
3import QuizScreen from 'screens/QuizScreen'
4
5const App = () => {
6 const [showResultModal, setShowResultModal] = useState<boolean>(false)
7
8 return (
9 <div>
10 <QuizScreen />
11 {showResultModal && <ModalWrapper title="SHOW RESULT" />}
12 </div>
13 )
14}
15
16export default AppIndividual Component to Make Conditional Rendering Easier
We can simplify this by writing a component for conditional rendering.
This is just a personal choice to use Conditional component.
1import { useState } from 'react'
2import Modal from 'ui/Modal'
3import QuizScreen from 'screens/QuizScreen'
4
5interface ConditionalProps {
6 when: boolean
7 component: React.ComponentType
8}
9
10const Conditional: React.FC<ConditionalProps> = ({ when, component: Component }) =>
11 when ? <Component /> : null
12
13const App = () => {
14 const [showResult, setShowResult] = useState<boolean>(false)
15
16 return (
17 <div>
18 <QuizScreen />
19 <Conditional when={showResult} component={Modal} />
20 </div>
21 )
22}
23
24export default App2. React Conditional Rendering with Ternary (Case #2):
When we need to toggle between two components, in this case, we handle conditional rendering in React with ternary operator.
In some scenarios, you might need to toggle between two components, displaying one while hiding the other based on user interactions or state changes.
A common example is showing a dashboard when a user is logged in, otherwise show a login screen.
Here's a simple example:
1const Dashboard = () => <p>Dashboard Screen</p>
2const Login = () => <p>Login Screen</p>
3
4const App = () => {
5 const [isLoggedIn, setIsLoggedIn] = useState < boolean > false
6
7 return <div>{isLoggedIn ? <Dashboard /> : <Login />}</div>
8}
9
10export default AppSimplifying Component Toggling with Individual Component
You can also simplify this using a ConditionalRender component:
1const Dashboard = () => <p>Dashboard Screen</p>
2const Login = () => <p>Login Screen</p>
3
4interface ConditionalRenderProps {
5 when: boolean
6 trueComponent: React.ComponentType
7 falseComponent: React.ComponentType
8}
9
10const ConditionalRender: React.FC<ConditionalRenderProps> = ({
11 when,
12 trueComponent: TrueComponent,
13 falseComponent: FalseComponent,
14}) => (when ? <TrueComponent /> : <FalseComponent />)
15
16const App = () => {
17 const [isLoggedIn, setIsLoggedIn] = useState<boolean>(true)
18
19 return (
20 <div>
21 <ConditionalRender when={isLoggedIn} trueComponent={Dashboard} falseComponent={Login} />
22 </div>
23 )
24}
25
26export default AppNote
We can only pass components as props, not JSX. In case you want to render JSX conditionally, you will need to return children in the ConditionalRender component.
3. Rendering Multiple Components Conditionally with Switch (Case #3)
In case we have to deal with more than two components in react, we can use various strategies like conditional rendering with if-else statements, a switch statement, or a JavaScript object mapping.
First, we will see an example using a switch statement:
1import { useEffect } from 'react'
2import { useQuiz } from '../../context/QuizContext'
3
4import QuestionScreen from '../QuestionScreen'
5import QuizDetailsScreen from '../QuizDetailsScreen'
6import QuizTopicsScreen from '../QuizTopicsScreen'
7import ResultScreen from '../ResultScreen'
8import SplashScreen from '../SplashScreen'
9
10export enum ScreenTypes {
11 SplashScreen,
12 QuizTopicsScreen,
13 QuizDetailsScreen,
14 QuestionScreen,
15 ResultScreen,
16}
17
18function Main() {
19 const { currentScreen, setCurrentScreen } = useQuiz()
20
21 useEffect(() => {
22 setTimeout(() => {
23 setCurrentScreen(ScreenTypes.QuizTopicsScreen)
24 }, 1000)
25 }, [setCurrentScreen])
26
27 switch (currentScreen) {
28 case ScreenTypes.SplashScreen:
29 return <SplashScreen />
30 case ScreenTypes.QuizTopicsScreen:
31 return <QuizTopicsScreen />
32 case ScreenTypes.QuizDetailsScreen:
33 return <QuizDetailsScreen />
34 case ScreenTypes.QuestionScreen:
35 return <QuestionScreen />
36 case ScreenTypes.ResultScreen:
37 return <ResultScreen />
38 default:
39 return <SplashScreen />
40 }
41}
42
43export default MainDynamic Component Rendering in React using Object with Typescript Enum
The above code can be simplified and made cleaner by using a JavaScript object. It's considered a best practice to render multiple conditions in ReactJS.
1import { useEffect } from 'react'
2import { useQuiz } from '../../context/QuizContext'
3
4import QuestionScreen from '../QuestionScreen'
5import QuizDetailsScreen from '../QuizDetailsScreen'
6import QuizTopicsScreen from '../QuizTopicsScreen'
7import ResultScreen from '../ResultScreen'
8import SplashScreen from '../SplashScreen'
9
10export enum ScreenTypes {
11 SplashScreen,
12 QuizTopicsScreen,
13 QuizDetailsScreen,
14 QuestionScreen,
15 ResultScreen,
16}
17
18function Main() {
19 const { currentScreen, setCurrentScreen } = useQuiz()
20
21 useEffect(() => {
22 setTimeout(() => {
23 setCurrentScreen(ScreenTypes.QuizTopicsScreen)
24 }, 1000)
25 }, [setCurrentScreen])
26
27 const screenComponents = {
28 [ScreenTypes.SplashScreen]: <SplashScreen />,
29 [ScreenTypes.QuizTopicsScreen]: <QuizTopicsScreen />,
30 [ScreenTypes.QuizDetailsScreen]: <QuizDetailsScreen />,
31 [ScreenTypes.QuestionScreen]: <QuestionScreen />,
32 [ScreenTypes.ResultScreen]: <ResultScreen />,
33 }
34
35 const ComponentToRender = screenComponents[currentScreen] || <SplashScreen />
36
37 return <>{ComponentToRender}</>
38}
39
40export default MainThese examples show different ways to do conditional rendering in React, so you can pick the one that fits your needs and coding style.
Feel free to reach out to me via email at abdul_basit313@outlook.com or LinkedIn for questions, suggestions, or if you would like to have a conversation. I'll be happy to respond.
Written by
Abdul Basit
Frontend developer passionate about JavaScript, React, and building great web experiences. Writing about web development to help developers level up their skills.
Continue reading
