import{jsx}from"react/jsx-runtime";import{Fragment}from"react";constIf=({children,condition})=>condition?jsx(Fragment,{children}):undefined;constDisplayData=({data})=>jsx(Fragment,{children:data});constdata=undefined;// The important bit:exportdefaultjsx(If,{condition:data,children:jsx(DisplayData,{data}),});
import{jsx}from"react/jsx-runtime";import{Fragment}from"react";constDisplayData=({data})=>jsx(Fragment,{children:data});constdata=undefined;// The important bit:exportdefaultdata?jsx(DisplayData,{data}):undefined;
With If you always call jsx with DisplayData passing data, without If you only do that call if data exists, if not you don't do anything.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Yes, it will cause an error. But it helps you write code in a more clean way. For example:
Since you will get an error by doing this way.
It forced you to do things like this which results a cleaner code:
Also, you can always check each property, but that is not recommended
Instead of having a component, you could have an util:
And then you use it like this:
Behaves similarly to your
Ifcomponent, but it only callsrenderifconditionis truthy, so there's a lot of issues you wouldn't have :DI just don't like the {...} things inside my JSX, it just doesn't look nice in terms of format.
JSX will always end up with
{...}somewhere. You can always use stuff like Svelte, that already includes "if" in their templating ☺️I wanted to add the same comment about the content of the
<If>being evaluated immediatelyand got some quite surprising results.
See here: codesandbox.io/s/if-component-b5zxk
Yes, a good example of how it works
If you understand the underlying code for React, then this is no surprise. When you write:
You're actually writing this:
Compared to doing it with a ternary like this:
That's like writing this:
With
Ifyou always calljsxwithDisplayDatapassingdata, withoutIfyou only do that call ifdataexists, if not you don't do anything.