Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Typescript: return array of Jsx elements

I'm trying React and TypeScript, but there's little information.

I have this situation in JavaScript:

render: function() {

  var stars = [];

  for (var idx = 1; idx <= this.state.max; idx++) {
    var fill = idx <= this.props.data.score;
    var hover = idx <= this.state.hoverIndex;
    stars.push(<RatingStar fill={fill} index={idx} data={this.props.data} hoverFill={hover} hover={this.hoverStar} leave={this.leaveStar} />);
  }
  return stars;


}

This is easy in plain JavaScript. I simply return an array of elements. But in TypeScript this code gives me an error because render() returns a single JSX element, not an array. If I change the return type to array of JSX element, the error is class doesn't implement React.component... So any idea?

like image 839
LXG Avatar asked Oct 04 '16 06:10

LXG


People also ask

How do you display an array of elements in JSX?

To render multiple JSX elements in React, you can loop through an array with the . map() method and return a single element. In the next example, you will examine why you would want to add a unique key to a list of elements rendered by an array.

What is IntrinsicAttributes in TypeScript?

IntrinsicAttributes interface can be used to specify extra properties used by the JSX framework which are not generally used by the components' props or arguments - for instance key in React.

What is the difference between TSX and JSX?

. tsx is similar to jsx except it's TypeScript with the JSX language extension.


1 Answers

Update

This will work React 16 and latest TypeScript definitions. The below answer is preserved for people on React 15 and below 🌹

Old Answer

render() return a single JSX element not an array

This is TypeScript actually helping you. you must return a single element from the render.

Fix

Consider wrapping the output in a div. This might break your css so you need to think about reorganizing that as well.

Alternatively don't create a component and just {callFoo()} in JSX instead of <Foo/>.

like image 186
basarat Avatar answered Nov 15 '22 05:11

basarat