Last updated: Feb 29, 2024
Reading timeยท2 min
The React.js error "Type {children: Element} has no properties in common with
type IntrinsicAttributes" occurs when we try to pass a children
prop to a
component that doesn't take any props.
To solve the error define and type the props on the component.
Here is an example of how the error occurs.
const Box = () => { // ๐๏ธ takes no props return ( <div> <p>Hello world</p> </div> ); }; const App = () => { return ( <div className="App"> {/* โ๏ธ Error: Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'. ts(2559) */} <Box> <span>Test</span> </Box> </div> ); }; export default App;
Notice that the Box
component doesn't take any props, but we are trying to
pass a children
prop to it.
children
prop.<MyComponent> Some children here </MyComponent>
One way to solve the error is to use the component as <Box />
if it doesn't
need to take any children.
const Box = () => { return ( <div> <p>Hello world</p> </div> ); }; const App = () => { return ( <div className="App"> <Box /> </div> ); }; export default App;
This solves the error because no children
props are being passed.
children
props before passing themHowever, if your component has to take a children
prop, you have to type it
when declaring the component.
import React from 'react'; type BoxProps = { children: React.ReactNode; // ๐๏ธ type children }; const Box = (props: BoxProps) => { return <div>{props.children}</div>; }; const App = () => { return ( <div className="App"> <Box> <span>Hello</span> <span>Test</span> </Box> </div> ); }; export default App;
We defined and typed a children prop on the Box
component which solves the
error.
Now the Box
component can be passed children
and render them.
any
typeIf you don't want to explicitly have to type the props and just want to turn off
type checking, you can set the props
object to any
type.
const Box = (props: any) => { // ๐๏ธ turns off type checking for props return <div>{props.children}</div>; }; const App = () => { return ( <div className="App"> <Box> <span>Hello</span> <span>Test</span> </Box> </div> ); }; export default App;
Anytime you use a component as:
<MyComponent> Some children </MyComponent>
You have to define and type the children
property on the specific component.
import React from 'react'; type BoxProps = { children: React.ReactNode; // ๐๏ธ define children prop }; const Box = (props: BoxProps) => { return <div>{props.children}</div>; }; const App = () => { return ( <div className="App"> <Box> <span>Hello</span> <span>Test</span> </Box> </div> ); }; export default App;
If you don't need to pass any children to your component, simply use the
component as <MyComponent />
.
const Box = () => { return <div>Hello world</div>; }; const App = () => { return ( <div className="App"> <Box /> </div> ); }; export default App;
If you get the error Type '() => JSX.Element[]' is not assignable to type FunctionComponent, click on the link and follow the instructions.