This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
After using Vue and Angular.js (I used the first version of Angular when it came out) for many years, I have to say that I always enjoyed the simplicity of using v-if
and ng-if
to render child components conditionally.
Now I'm writing React primarily and I'm bothered by the constant use of ternary operators when dealing with conditionally rendered components.
function SomeComponent({condition}) {
return <div>
{ condition ? <span>Yes it is true!</span> : null }
</div>
}
It's not a big deal, and there are many different ways to render boolean-dependent components (such as using &&
), but I never really liked writing code like this and I don't think it's very readable.
Today I read 7 Ways of Achieving Conditional Rendering in React, and it included a handy snippet that I'll adopt from now on.
A conditional if
component
Section titled A conditional `if` component
I can't say that I didn't consider abstracting the ternary operators away, but somehow I never took it into practice. Fernando Doglio's article now moved me over the line to adopt a nicer pattern. Say hi to the functional if
component.
function IF({children, condition}) {
if (condition) {
// render children if the condition is truthy
return children;
}
return null;
}
/**
* Use the component as follows:
*
* <IF condition={condition}>
* <Greeter username={user.name} />
* </IF>
*/
It's seven lines of code and this tiny component can be brought into any React project as a handy utility. Much better! Thank you Fernando!
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2021-01-23T23:00:00+00:00) A React "if component" (#snippet). Retrieved from https://www.scien.cx/2021/01/23/a-react-if-component-snippet/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.