Take a look at this simple example:
const List = function({ loading, entity }) {
return (
<Layout loading={loading}>
<span>Name: {entity.name}</span>
</Layout>
);
};
Layout
component is rendering its children
only when loading
is false
. But the problem here is that React
is resolving Layout
children immediatelly. Since entity
is null
(while loading=true
) I get error that it can't read name
of null
. Is there a simple way to avoid this error since this span
will always be rendered when entity
is not null
?
Currently I know about 3 options:
span
to stateless function
which receives entity
as prop
children
of Layout
in function
and then support function children
in Layout
{entity && <span>Name: {entity.name}</span>}
Why do I have to use one of these options and can I make React
to consider those children
as function and resolve block inside later on before the render?
The React. lazy function lets you render a dynamic import as a regular component.
Suspense is a component for wrapping lazy components. You can wrap multiple lazy components at different hierarchy levels with a single Suspense component. The Suspense component takes a fallback prop that accepts the React elements you want rendered as placeholder content while all the lazy components get loaded.
It enables us to load the content just in time, right before it will be displayed in the application. We can avoid pre-loading content while it's still out of view, and focus all of the resources on the content that is in the view. In this guide, we'll look at how to use React. lazy() and React.
What are children? The children, in React, refer to the generic box whose contents are unknown until they're passed from the parent component. What does this mean? It simply means that the component will display whatever is included in between the opening and closing tags while invoking the component.
I just stumbled upon the same problem.
What worked for me was passing children as a function:
ready: boolean;
children?: () => ReactNode,
}> = ({ ready, children }) => {
return (
<div>{
ready ?
children() :
(
<div>not ready</div>
)
}</div>
);
};
<Layout loading={loading}>
{() =>
<span>Name: {entity.name}</span>
}
</Layout>
Though it's still not perfect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With