DEV Community

Cover image for Write if else in react (Conditional Rendering)
Aastha Pandey
Aastha Pandey

Posted on

3 1

Write if else in react (Conditional Rendering)

I was trying to search like this "How to write if else in react".
Then got to know about conditional rendering.
When to use conditional rendering?
If one wants to render a component based on some state change or when some condition becomes true.

In the below code conditional rendering has been done, it's first checking if isLoggedIn is true then it'll render the About component else if it's false Home component will be rendered.


//MyComponent.js
import React, {useState} from "react"
import Home from "./Home"
import About from "./About"
const MyComponent = () => {
const [isLoggedIn, setIsLoggedIn] = useState();
 return <>
{
 isLoggedIn ? (<About/>) : (<Home/>)
}
</>
}
export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

or


//MyComponent.js

import React, {useState} from "react"
import About from "./About"
import Home from "./Home"
const MyComponent = () => {
const [isLoggedIn, setIsLoggedIn] = useState();
 if(isLoggedIn) {
    return <About/>
  }else {
    return <Home/>
  }
}
export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

The code above will always render the Home component since I'm not changing the state isLoggedIn from false to true.

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay