This content originally appeared on DEV Community and was authored by Redžep Murati
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).
Let’s 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 it’s 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 ❤️
This content originally appeared on DEV Community and was authored by Redžep Murati
Redžep Murati | Sciencx (2021-07-08T07:43:03+00:00) Simplify condition rendering in React.js. Retrieved from https://www.scien.cx/2021/07/08/simplify-condition-rendering-in-react-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.