10

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?

Sarun UK
  • 6,210
  • 7
  • 23
  • 48
zhuber
  • 101
  • 3
  • what is the goal? lazy loading? request the chunk file only when the user reach the component? Or request the chunk only if the var loading is enabled? – Leonardo Lima Sep 16 '20 at 13:54

1 Answers1

1

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.

yurique
  • 43
  • 4