0

I have been working with React JS & Flow for quite a bit and now, recently switching over to typescript. I am not sure why typescript complains on the Stateless Component Definition.

Source

interface Test2Prop {
  names : string[];
}

const TestComponent: SFC<TestProp> = (props: TestProp) => {
    return (
        props.name.map((val, idx) => <h3 key={idx}>{`APPENDING-${val}`}</h3>)
    );
}

Error

[ts]
Type '(props: TestProp) => Element[]' is not assignable to type 'FunctionComponent<TestProp>'.
  Type 'Element[]' is not assignable to type 'ReactElement<any>'.
    Property 'type' is missing in type 'Element[]'. [2322]

And I am not sure why using React.Fragment makes the error go away.

interface Test2Prop {
  names : string[];
}

const Tests : React.SFC<Test2Prop> = (props : Test2Prop) => {
  return (
    <React.Fragment>
    { props.names.map(name => <h1>{name}</h1>) }
    </React.Fragment>
  ); 
}

I don't want to use React.Fragment as that is not a solution but a hack as per my understanding.

Stackblitz here

Ashish Santikari
  • 443
  • 4
  • 19
  • Perhaps you're using out-of-date React types? React 15 didn't allow an SFC (or a component's `render`) to return an array, that feature was added in React 16... – T.J. Crowder Dec 16 '18 at 11:12
  • 1
    I checked my package.json and my react types version is 16.7.17. – Ashish Santikari Dec 16 '18 at 11:15
  • The render component should return one element. If you use a map, it will return an array of elements. So you have to wrap the map with something. One solution is div and the other is fragment. So it is not a hack it is the solution to a problem. – Peter Ambruzs Dec 16 '18 at 11:22
  • Makes sense @PeterAmbruzs. – Ashish Santikari Dec 16 '18 at 11:25
  • 1
    Is it said clearly by the error you get - `Element[]` is not assignable to `ReactElement`. Adjacent elements must be wrapped. And using `React.Fragment` is not a hack. – kind user Dec 16 '18 at 11:26
  • Possible duplicate of [Return react 16 array elements in typescript](https://stackoverflow.com/questions/46643517/return-react-16-array-elements-in-typescript) – Agney Dec 16 '18 at 12:34
  • React allows you to return an array of elements, but Typescript hasn't been upgraded to the [change](https://github.com/Microsoft/TypeScript/issues/21699) – Agney Dec 16 '18 at 12:35

0 Answers0