Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lazy render children

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:

  1. Move this span to stateless function which receives entity as prop
  2. Wrap whole children of Layout in function and then support function children in Layout
  3. Just use {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?

like image 997
zhuber Avatar asked Dec 04 '18 13:12

zhuber


People also ask

What is lazy () in React?

The React. lazy function lets you render a dynamic import as a regular component.

What is suspense and lazy in React?

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.

Why is reacting lazy loading?

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 is a React child?

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.


1 Answers

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.

like image 147
yurique Avatar answered Oct 06 '22 20:10

yurique