This content originally appeared on DEV Community and was authored by Ahmedammarr
Lately, I've been looking for a better way to write clean conditional rendering code instead of ternary and && operators and even if statements, because sometimes they can be confusing and I found that I can write the same functionality with objects, it makes the code more readable. let's see how we can write a well-typed object to render a component based on the parent component state and props
export default function Products({state}:ProductsStateEnum)
:ReactElement {
const [_ProductsState, setProductsState] = useState(state)
const ProductsState: { [key in ProductsStateEnum]: ReactElement } = {
loading: <Loader width={150} />,
failed: (
<div>
<Badge bg='danger'>Somethig Went Wrong</Badge>
</div>
),
done: (
<>
{products?.map(
({ id, title, image, description, category, price }) => (
<ProductCard
key={id}
id={id}
title={title}
description={description}
category={category}
price={price}
image={image}
/>
)
)}
</>
)
}
return <div className='row p-3'>{ProductsState[_ProductsState]}</div>
}
We notice here that we didn't write any if statement or any operator, based on the state the component will render the React component with key that's equal to the _ProductsState, tell me if you know another way to write readable conditional rendering options!
This content originally appeared on DEV Community and was authored by Ahmedammarr

Ahmedammarr | Sciencx (2021-10-19T23:34:10+00:00) React Typescript conditional rendering using objects. Retrieved from https://www.scien.cx/2021/10/19/react-typescript-conditional-rendering-using-objects/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.