13 Conditional Rendering - biswajitsundara/react GitHub Wiki
React allows us to display components or elements of a component if the condition is true or false.
- Conditional rendering in React works the same way conditions work in JavaScript.
- We can place conditions on components or in JSX
Lets say we want to render SingleCard component if the user is single and MarriedCard component if married.
// SingleCard.js
export const SingleCard = () => {
return <h1>Hi I am single!</h1>;
}
// MarriedCard.js
export const MarriedCard = () =>{
return <h1>Hello,I am married</h1>;
}
// MaritalStatus.js
import {SingleCard} from '../conditional rendering/SingleCard';
import {MarriedCard} from '../conditional rendering/MarriedCard';
export const MaritalStatus = () =>{
let isMarried = true;
if(isMarried){
return <MarriedCard />;
}
else{
return <SingleCard />;
}
}
//App.js
import { MaritalStatus } from "./components/conditional rendering/MaritalStatus";
function App() {
return <MaritalStatus/>;
}
export default App;
We can setup the condition using ternary operator also. We can rewrite the MaritalStatus component.
import { SingleCard } from "../conditional rendering/SingleCard";
import { MarriedCard } from "../conditional rendering/MarriedCard";
export const MaritalStatus = () => {
let isMarried = true;
return (
<>
{ isMarried ? <MarriedCard /> : <SingleCard /> }
</>
);
};
If we combine two things using && operator -
- If the first condition satisfies then only the second part will be evaluated.
- If the first condition fails then it will not go to the second part
- So we can construct our logic this way
condition && component - Lets say here, we want to display the married component only when the person is married.
import { MarriedCard } from "../conditional rendering/MarriedCard";
export const MaritalStatus = () => {
let isMarried = true;
return (
<>
{
isMarried &&
<MarriedCard />
}
</>
)
};