Fix – react.children.only expected to receive a single react element child
Posted on: February 21, 2021 by Pandu Rijal Pasa
If you get react.children.only expected to receive a single react element child error, here is how to fix this issue.
The issue happened because the component only expects a single ReactElement
to its children. Here is an example that could give you a similar error:
<MyComponent>
<div>First Children</div>
<div>Second Children</div>
</MyComponent>
To fix the issue, don’t put more than one element on your children. If you still need to keep those multiple elements as children without any wrapper element, you can use ReactFragment
to replace the wrapper. Here is an example to do that:
// using ReactFragment
<MyComponent>
<React.Fragment>
<div>First Children</div>
<div>Second Children</div>
</React.Fragment>
</MyComponent>
// using short syntax of ReactFragment
<MyComponent>
<>
<div>First Children</div>
<div>Second Children</div>
</>
</MyComponent>
Share on social media
//