On This Page
- # Why is conditional rendering in React JS important?
- # 3 Cases of React JS Conditional Rendering
- # 1. Displaying a Component Conditionally (Case #1):
- # Individual Component to Make Conditional Rendering Easier
- # 2. React Toggling Between Two Components (Case #2):
- # Simplifying Component Toggling with Individual Component
- # 3. Efficiently Rendering Multiple Components in React Conditionally (Case #3)
- # Dynamic Component Rendering Strategies in React
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 alos 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:
import { useState } from 'react'import ModalWrapper from 'ui/ModalWrapper'import QuizScreen from 'screens/QuizScreen'const App = () => {const [showResultModal, setShowResultModal] = useState<boolean>(false)return (<div><QuizScreen />{showResultModal && <ModalWrapper title="SHOW RESULT" />}</div>)}export default App
Individual 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.
import { useState } from 'react'import Modal from 'ui/Modal'import QuizScreen from 'screens/QuizScreen'interface ConditionalProps {when: booleancomponent: React.ComponentType}const Conditional: React.FC<ConditionalProps> = ({ when, component: Component }) =>when ? <Component /> : nullconst App = () => {const [showResult, setShowResult] = useState<boolean>(false)return (<div><QuizScreen /><Conditional when={showResult} component={Modal} /></div>)}export default App
2. React Toggling Between Two Components (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:
const Dashboard = () => <p>Dashboard Screen</p>const Login = () => <p>Login Screen</p>const App = () => {const [isLoggedIn, setIsLoggedIn] = useState < boolean > falsereturn <div>{isLoggedIn ? <Dashboard /> : <Login />}</div>}export default App
Simplifying Component Toggling with Individual Component
You can also simplify this using a ConditionalRender
component:
const Dashboard = () => <p>Dashboard Screen</p>const Login = () => <p>Login Screen</p>interface ConditionalRenderProps {when: booleantrueComponent: React.ComponentTypefalseComponent: React.ComponentType}const ConditionalRender: React.FC<ConditionalRenderProps> = ({when,trueComponent: TrueComponent,falseComponent: FalseComponent,}) => (when ? <TrueComponent /> : <FalseComponent />)const App = () => {const [isLoggedIn, setIsLoggedIn] = useState<boolean>(true)return (<div><ConditionalRender when={isLoggedIn} trueComponent={Dashboard} falseComponent={Login} /></div>)}export default App
Note
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. Efficiently Rendering Multiple Components in React Conditionally (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:
import { useEffect } from 'react'import { useQuiz } from '../../context/QuizContext'import QuestionScreen from '../QuestionScreen'import QuizDetailsScreen from '../QuizDetailsScreen'import QuizTopicsScreen from '../QuizTopicsScreen'import ResultScreen from '../ResultScreen'import SplashScreen from '../SplashScreen'export enum ScreenTypes {SplashScreen,QuizTopicsScreen,QuizDetailsScreen,QuestionScreen,ResultScreen,}function Main() {const { currentScreen, setCurrentScreen } = useQuiz()useEffect(() => {setTimeout(() => {setCurrentScreen(ScreenTypes.QuizTopicsScreen)}, 1000)}, [setCurrentScreen])switch (currentScreen) {case ScreenTypes.SplashScreen:return <SplashScreen />case ScreenTypes.QuizTopicsScreen:return <QuizTopicsScreen />case ScreenTypes.QuizDetailsScreen:return <QuizDetailsScreen />case ScreenTypes.QuestionScreen:return <QuestionScreen />case ScreenTypes.ResultScreen:return <ResultScreen />default:return <SplashScreen />}}export default Main
Dynamic Component Rendering Strategies in React
The above code can be simplified and cleaner by using a JavaScript object:
import { useEffect } from 'react'import { useQuiz } from '../../context/QuizContext'import QuestionScreen from '../QuestionScreen'import QuizDetailsScreen from '../QuizDetailsScreen'import QuizTopicsScreen from '../QuizTopicsScreen'import ResultScreen from '../ResultScreen'import SplashScreen from '../SplashScreen'export enum ScreenTypes {SplashScreen,QuizTopicsScreen,QuizDetailsScreen,QuestionScreen,ResultScreen,}function Main() {const { currentScreen, setCurrentScreen } = useQuiz()useEffect(() => {setTimeout(() => {setCurrentScreen(ScreenTypes.QuizTopicsScreen)}, 1000)}, [setCurrentScreen])const screenComponents = {[ScreenTypes.SplashScreen]: <SplashScreen />,[ScreenTypes.QuizTopicsScreen]: <QuizTopicsScreen />,[ScreenTypes.QuizDetailsScreen]: <QuizDetailsScreen />,[ScreenTypes.QuestionScreen]: <QuestionScreen />,[ScreenTypes.ResultScreen]: <ResultScreen />,}const ComponentToRender = screenComponents[currentScreen] || <SplashScreen />return <>{ComponentToRender}</>}export default Main
These 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 [email protected] or LinkedIn for questions, suggestions, or if you would like to have a conversation. I'll be happy to respond.