Using Suspense & lazy triggers warning about functions are not valid as react child
See original GitHub issueDo you want to request a feature or report a bug? A bug.
What is the current behavior?
Using <Suspense />
& lazy
to lazy load components triggers the following warning:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
It does however not affect functionality at all and the lazy loading & rendering of the component works fine.
**If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. https://codesandbox.io/s/mjzj27m0j8
What is the expected behavior? Not trigger the warning as this should be a valid way of loading & rendering components according to the documentation.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
react@16.6.0
react-dom@16.6.0
react-scripts@2.0.3
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:7 (3 by maintainers)
Hey @rovansteen! This is expected behavior, and the fix that @frehner provided is the correct way to do it.
Suspense
expects that thefallback
prop will be a React element not a React component. When you do:You’re passing in a function component that renders a
div
with some text. What you need to do is pass what that function would return directlyWhich is why @frehner’s change works because
<Loading />
is a React element for theLoading
component.You can think of
Suspense
as working something like:So think of it just like you would children. What you’re doing is equivalent to doing something like:
Hopefully that makes it clear why React would warn about that function not being a valid child.
Thanks for the explanation @aweary. I misread the documentation that correctly describes returning the component directly rather than a function. I was just confused because it did not crash and the loading of the component was too fast to see or notice the fallback. Cheers!