Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 19, 2021 11:34 pm GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To