An Interest In:
Web News this Week
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
October 19, 2021 11:34 pm GMT
Original Link: https://dev.to/ahmeddammarr/react-typescript-conditional-rendering-using-objects-156l
React Typescript conditional rendering using objects
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!
Original Link: https://dev.to/ahmeddammarr/react-typescript-conditional-rendering-using-objects-156l
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