Conditional Rendering
As we can understand from the term, conditional rendering is a way to render different JSX or component at different condition. We can implement conditional rendering using regular if and else statement, ternary operator and &&. Let's implement a different conditional rendering.
Conditional Rendering using If and Else statement
The problem with using if and else statements is that you are not allowed to use hooks afterwards.
Example
An if- and else statement inside a React component is done mostly at the bottom of the component. See an example here:
Example
const Component = () => {
const { isLoggedIn, isLoading } = React.useContext(AuthenticationContext)
const [someState, setSomeState] = React.useState(false)
if (!isLoggedIn) {
return <p>You are not allowed to see this</p>
}
if (!isLoading) {
return <p>Loading...</p>
}
return (
<p
onClick={() => {
setSomeState(!someState)
}}
>
Currently its: {someState}
</p>
)
}
Ternary operator
In most cases you want to switch inside your component between different views. Therefore you will use the conditional operator the OR operator or the AND Operator.
Here are some examples:
Example
Example