头图

The text starts here~

Overview

When we try to return an array of elements from a function component, the error "Type '() => JSX.Element[]' is not assignable to type FunctionComponent" is generated. To get around that error, you can wrap the element array in a React fragment.

jsx-element-not-assignable-type-functioncomponent.png

Here is an example to show how the error occurs.

 // App.tsx
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 because we are able to return an array from React's function component. However, the return type of the --- FunctionComponent interface is ReactElement or null .

This means that we can just return a React element or null value.

React Fragments

To fix that type error, we have to wrap the array in a React fragment .

 // App.tsx
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.

React.Fragment

You may also see more verbose snippet syntax used.

 // App.tsx
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 elements of the element list without adding extra nodes to the DOM.

div

Another solution is to wrap the array of elements in another DOM element, such as a div.

 // App.tsx
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 matches the return type specified in the FunctionComponent interface, since our component returns a single React element.

Summarize

To get around the "Type '() => JSX.Element[]' is not assignable to type FunctionComponent" error, you can use React snippets or div to wrap the array of elements.


chuck
303 声望41 粉丝