I want to use the new react 16 feature to return array elements in my render
but i'm getting the typescript error Property 'type' is missing in type 'Element[]'
const Elements: StatelessComponent<{}> = () => ([
<div key="a"></div>,
<div key="b"></div>
]);
What am i missing? Using @types/react 16.0.10 and typescript 2.5.3
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.
Since v16. 0, React allows us to return multiple elements from the render function by wrapping them in an array. In previous versions, it was necessary to wrap multiple elements into a single parent, which resulted in an extra node appearing in the DOM tree.
Use square brackets to get the first element of an array in React, e.g. const first = arr[0]; . The array element at index 0 is the first element in the array. If the array is empty, an undefined value is returned.
createElement() Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span' ), a React component type (a class or a function), or a React fragment type. Code written with JSX will be converted to use React.
Normally, when writing a React application in TypeScript, assigning return type to components is unnecessary. However, sometimes it’s necessary to do so. For instance, a company-wide linting rule might require developers to specify the return type for components. This article will discuss the three types that can apply to components.
Return multiple elements in @reactjs 16 ❤️ #js #javascript #react #reactjs pic.twitter.com/uPGyxUGtWn The basic way is to return an array of elements. To avoid warnings you have to add a key to each element, although it may not be needed in the future.
To declare a function with an array return type, set the return type of the function to an array right after the function's parameter list, e.g. function getArr (): string [] {}. If the return type of the function is not set, TypeScript will infer it.
The render () functions of functional components return the ReactElement type. If you must assign a type to functional components in React, it should be this one. If there’s a chance that the component will return null, you should use the or || operator to assign it the type ReactElement || null.
Or use React fragments:
render() {
return
<>
<div key="a"></div>,
<div key="b"></div>
</>
}
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