An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
May 29, 2021 09:18 am GMT
Original Link: https://dev.to/aasthapandey/write-if-else-in-react-conditional-rendering-272n
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.jsimport 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;
or
//MyComponent.jsimport 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;
The code above will always render the Home component since I'm not changing the state isLoggedIn from false to true.
Original Link: https://dev.to/aasthapandey/write-if-else-in-react-conditional-rendering-272n
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To