Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript + React, rendering an array from a stateless functional component

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.

like image 669
Edo Avatar asked Oct 12 '17 12:10

Edo


People also ask

Are React functional components stateless?

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.

Can stateless components have functions?

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.

Can you render an array of components React?

To render multiple JSX elements in React, you can loop through an array with the . map() method and return a single element.

How do you pass an array as a prop in a functional component?

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.


1 Answers

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>
  );
};
like image 61
NSjonas Avatar answered Oct 08 '22 23:10

NSjonas