The React team announced that since React 16:
You can now return an array of elements from a component’s render method.
This works in typescript for regular class components, but I cannot get it to work for stateless functional components.
See this repo if you want to reproduce for yourself.
Code:
import * as React from 'react';
// See this example working in a non-TS environment: https://codesandbox.io/s/ppl3wopo8j
class Hello extends React.Component {
render() {
return <div>
<Foo />
<Bar /> {/* Error: 'JSX element type 'Element[]' is not a constructor function for JSX elements. */}
</div>;
}
}
class Foo extends React.Component {
render() {
return [<div>foo</div>, <div>fooz</div>];
}
}
function Bar() {
// Cannot render an array from a SFC
return [<div>bar</div>, <div>baz</div>];
}
Building this snipper results in the following error:
'JSX element type 'Element[]' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Element[]'.'
As you can see, rendering an array from a regular class component works, but it fails when rendering an array from a stateless functional component.
I'm unsure whether the problem lies with my code/setup, the DefinitelyTyped react types, or with typescript itself.
A functional component is always a stateless component, but the class component can be stateless or stateful. There are many distinct names to stateful and stateless components.
Stateless Components The idea with a stateless functional component is that it is state-less and just a function. So what's great about this is that you are defining your component as a constant function that returns some data. In simple words, stateless functional components are just functions that return JSX.
To render multiple JSX elements in React, you can loop through an array with the . map() method and return a single element.
To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements.
Until the open Definitely Typed issue has been resolved, the best work around is probably just to use <React.Fragment/>
instead. For functional purposes, I don't think there is any difference:
const Bar: React.SFC<CheckoutProps> = (props) => {
return (
<React.Fragment>
<div>bar</div>
<div>baz</div>
</React.Fragment>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With