An Interest In:
Web News this Week
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
- March 13, 2024
July 27, 2022 04:22 pm GMT
Original Link: https://dev.to/gax97/avoiding-large-ternary-operator-statements-in-react-4i19
Avoiding large ternary operator statements in React
Introducing the problem
Often when writing React applications, you are conditionally rendering some piece of UI based on some state.
This condition can be as simple as a binary boolean condition, or it can be a more complex ternary operator with multiple nested statements.
Let's imagine that we are calling an API using react-query and that we are displaying different UI depending on the API
call status.
const Example = () => { const { data, status } = useQuery('users', fetchUsers) return ( <Page> {status === 'loading' ? ( <LoadingView /> ) : status === 'error' ? ( <ErrorView /> ) : ( <SuccessView data={data} /> )} </Page> )}
These kinds of conditions can get hard to read sometimes.
Leveraging compound components and React.Children.map
function, we can write a cleaner solution by moving condition logic into a wrapper component.
const Example = () => { const { data, status } = useQuery('users', fetchUsers) return ( <Page.Wrapper status={status}> <Page.Loading> <LoadingView /> </Page.Loading> <Page.Error> <ErrorView /> </Page.Error> <Page.Success> <SuccessView data={data} /> </Page.Success> </Page.Wrapper> )}
Page component implementation
const PageWrapper = ({ children, status }) => { const renderChildren = useCallback(() => { return React.Children.map(children, (child) => { if (child?.type === Screen.Loading && status === 'loading') { return child } if (child?.type === Screen.Success && status === 'success') { return child } return null }) }, [children, status]) return <>{renderChildren()}</>}export const Page = { Wrapper: PageWrapper, Loading: ({ children }) => children, Success: ({ children }) => children, Error: ({ children }) => children,}
Originally published at: https://www.danilothedev.com/blog/avoiding-large-ternary-statements-in-react
Original Link: https://dev.to/gax97/avoiding-large-ternary-operator-statements-in-react-4i19
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