Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Conditional Rendering

User image

Published by

sanya sanya

Published at: 28th Jul, 2023
1.29 mins read

Conditional rendering in React.js allows you to display different content or components based on certain conditions.

It enables you to control what gets rendered to the DOM based on the state of your application. Here are a few common techniques for conditional rendering in React.

if/else Statements

We can use regular JavaScript if/else statements inside your render method to conditionally render different components or content.

render() { if (condition) { return ; } else { return ; } }

Ternary Operator

The ternary operator (condition ? expression1 : expression2) is another concise way to conditionally render content.

render() {
  return (
    <div>
      {condition ? <Component1 /> : <Component2 />}
    </div>
  );
}

Logical && Operator

We can use the logical AND (&&) operator to conditionally render content based on a condition. When the condition is true, the expression after && is evaluated and rendered. Otherwise, nothing is rendered.

render() { return (

{condition && }
); }


Using Variables

We can assign the content you want to render to a variable and conditionally use that variable in your JSX.

render() {
   let content;
   if (condition) {
     content = <Component1 />;
   } else {
     content = <Component2 />;
   }
 
   return <div>{content}</div>;
 }

Rendering Null or Empty Fragment

Returning null or an empty fragment (<>...</>) from the render method will cause nothing to be rendered.

render() { if (condition) { return null; } else { return ; } }

Library

WEB DEVELOPMENT

Basic

Frontend

Express JS

React

Hello World in ReactJS

Rendering Elements

States and Lifecycles in React JS

Handling Events in React JS

Introduction to JSX

Components and Props in React JS

Conditional Rendering

Lists and Keys in React JS

Introduction to Redux

Types of components (class vs functional)

Using the useEffect hook

Building custom hooks in React JS

Context API in React JS

Forms in React JS

Lifting State Up in React JS

Composition vs Inheritance

Prop drilling in React JS

Introduction to Hooks

Using the useState hook

UseMemo vs useCallback

Backend

Interview Questions

FAANG QUESTIONS

On this page

if/else Statements

Ternary Operator

Logical && Operator

Using Variables

Rendering Null or Empty Fragment