Last updated: Feb 29, 2024
Reading time·2 min
The React.js error "Type '() => JSX.Element[]' is not assignable to type FunctionComponent" occurs when we try to return an array of elements from a function component.
To solve the error, wrap the array of elements into a React fragment.
Here is an example of how the error occurs.
import React from 'react'; // ⛔️ Type '() => JSX.Element[]' is not assignable to type 'FunctionComponent<{}>'. // Type 'Element[]' is missing the following properties // from type 'ReactElement<any, any>': type, props, key ts(2322) const App: React.FunctionComponent = () => { return ['Alice', 'Bob'].map(element => <div key={element}>{element}</div>); }; export default App;
This is perfectly valid React.js code as we should be able to return an array from a function component in React.
However, the return type of the FunctionComponent
interface is ReactElement
or null
.
Therefore we can only return a React element or a null
value.
To get around the type error, we have to wrap the array in a React fragment.
import React from 'react'; const App: React.FunctionComponent = () => { return ( <> {['Alice', 'Bob'].map(element => ( <div key={element}>{element}</div> ))} </> ); }; export default App;
Fragments are used when we need to group a list of elements without adding extra nodes to the DOM.
You might also see the more verbose syntax of fragments being used.
import React from 'react'; const App: React.FunctionComponent = () => { return ( <React.Fragment> {['Alice', 'Bob'].map(element => ( <div key={element}>{element}</div> ))} </React.Fragment> ); }; export default App;
The two examples above achieve the same result - they group the list of elements elements without adding extra nodes to the DOM.
An alternative solution is to wrap the array of elements in another DOM element,
e.g. a div
.
import React from 'react'; const App: React.FunctionComponent = () => { return ( <div> {['Alice', 'Bob'].map(element => ( <div key={element}>{element}</div> ))} </div> ); }; export default App;
This still conforms to the specified in the FunctionComponent
interface return
type, because our component returns a single React element.