Render JSX Based on Truthiness
I move between different stacks and projects a lot at my job and inevitably have the same thought process happen every time I revisit React for the first time in a long time; If this state is true render this, else... well, I actually don't need to render a component for the other case.
Let's say we have a piece of state called admin and if it's true we render an extra component that shows some UI specific to an administator. I'll just use some generic naming for this example.
import React, { useState } from 'react';
import { AdminInterface } from '../AdminInterface;
export const CourseOverview = () => {
let [admin, setAdmin] = useState(false)
return (
<div>
{ admin ? <AdminInterface/> : ....null? }
</div>
)
}
In this case, we really don't have an alternate component because if admin is false we want to render nothing. A nice clean way to do this is with the && operator.
import React, { useState } from 'react';
import { AdminInterface } from '../AdminInterface;
export const CourseOverview = () => {
let [admin, setAdmin] = useState(false)
return (
<div>
{ admin && <AdminInterface/> }
</div>
)
}
The trick to using this operator the right way is to make sure that you aren't including components that you need to render reguardless of what the state is. If the state is false then nothing after && will render. The use case for this is specifically if admin is true render this; if admin is false render nothing.