LXG LXG - 11 months ago 226
TypeScript Question

React Typescript: return array of Jsx elements

I'm trying React and typescript, but there's few informations, by the way the question is this:

I 've in javascript this situation

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;


well, this is easy in plain javascript, I simply return an array of elements, but in typescript this code... give me an error because render() return a single JSX element not an array, and if I change return type to array of JSX element, the error : class not inplements React.component... so any idea


Answer Source

render() return a single JSX element not an array

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


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