Conditionally Render React Components in different ways.

Shahid Yousafxai
Nerd For Tech
Published in
2 min readOct 16, 2023
conditional rendering in react

In React, you can render components conditionally in various ways based on different conditions. Following are the three ways to conditionally render components in React. The method you choose may depend on your specific use case and the complexity of your conditions.

1. Using if Statements || Using a Ternary Operator.
2. Using a Switch Statement.
3. Using an Object Mapping.

Using if Statements || Using a Ternary Operator

This is the simplest way to render the react component Conditionally. Each component will be rendered on the base of the condition. if the condition isn’t met it will redirect you to the else statement.

Using if Statements || Using a Ternary Operator

Using a Switch Statement.

In JavaScript, the switch statement is used to execute different code blocks based on the value of the Expression || Condition. Switch Statment is particularly useful when you have multiple conditions to check against a single expression/condition, making the code more concise and readable compared to using a series of if…else if…else statements.

Using a Switch Statement.

Here case will check the condition and based on the condition it will render the component otherwise it will return the default component if the condition does not meet any case.

Using an Object Mapping.

Create an object having keys and components against the keys. The keys will act as a possible condition you will have. Assign the component to each key/condition you want to render against the key/condition.

Using an Object Mapping.

Pass your condition on the object value and it will return the component based on the condition. If the key is not there it will return the default component.

--

--

Shahid Yousafxai
Nerd For Tech

Software Engineer | Frontend Developer | Technical Writer