Last updated: Feb 29, 2024
Reading time·2 min
To solve the error "This JSX tag's 'children' prop expects a single child of
type 'Element', but multiple children were provided", use a fragment to wrap the
children props passed to the component or type the component's children prop as
React.ReactNode
.
Here is an example of how the error occurs.
type HeaderProps = { children: JSX.Element; }; function Header(props: HeaderProps) { return <div>{props.children}</div>; } function App() { return ( <div> {/* ⛔️ This JSX tag's 'children' prop expects a single child of type 'Element', but multiple children were provided.ts(2746) */} <Header> <h1>Hello</h1> <h1>World</h1> </Header> </div> ); } export default App;
The issue here is that we typed the Header
component's props to only take a
single child of type JSX.Element
, but we are passing multiple elements to it.
One way to solve the error is to use a fragment to wrap the component's children.
type HeaderProps = { children: JSX.Element; }; function Header(props: HeaderProps) { return <div>{props.children}</div>; } function App() { return ( <div> <Header> {/* 👇️ wrap in Fragment */} <> <h1>Hello</h1> <h1>World</h1> </> </Header> </div> ); } export default App;
We wrapped the multiple elements into a fragment, so we are only passing a
single child element to the Header
component, which solves the error.
If you forget to type the children
prop when using React TypeScript, you'd get
the
Property 'children' does not exist on type 'X'
error.
children
prop to solve the errorAn even better solution would be to type the component's children as
React.ReactNode
.
type HeaderProps = { children: React.ReactNode; }; function Header(props: HeaderProps) { return <div>{props.children}</div>; } function App() { return ( <div> <Header> <h1>Hello</h1> <h1>World</h1> </Header> </div> ); } export default App;
The React.ReactNode
type is much wider than just JSX.Element
.
The type is defined as:
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
Now we can pass multiple children to the Header
component without having to
wrap them in a fragment.