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?
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.
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.
. tsx is similar to jsx except it's TypeScript with the JSX language extension.
This will work React 16 and latest TypeScript definitions. The below answer is preserved for people on React 15 and below 🌹
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/>
.
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