An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
Simplify condition rendering in React.js
As a professional developer you are forced to stay up to date with the latest trends in technology. This year I've added Svelte to my bucket list as a new framework to learn.
While researching Svelte I was surprised by the way they handle condition rendering.
Take a look at this example found in their docs:
{#if user.loggedIn} <button on:click={toggle}> Log out </button> {/if}
Everything is neatly wrapped with if clause and separated from normal flow.
After a quick prototyping I present to you the most powerful component I have ever written, an IF component.
const IF = ({ condition, children }) => { if (!condition) return null; return <>{children}</>; };
By offloading condition into a separate component this will improve code cleanness and readability by quite a margin (for free).
Lets imagine the Svelte example in our React app. It would go something like this:
return ( <> {user.loggedIn && <button>Log out</button>} </> );...
This is not an end of the world issue when you have just one condition but as our apps grow, so do the conditions.
Take a look at the same component now refactored to use IF:
return ( <IF condition={user.loggedIn}> <button>Log out</button> </IF> );...
Now its easier to track down conditions and debug faulty ones, plus the code looks way cleaner now that conditions are gone from JSX.
Hope you found this helpful
Original Link: https://dev.to/ornio/simplify-condition-rendering-in-react-js-33l8
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To