score:159
Try to think of the tags as function calls (see the documentation). Then the first one becomes:
{[1,2,3].map(function (n) {
return React.DOM.p(...);
})}
And the second one:
{[1,2,3].map(function (n) {
return (
React.DOM.h3(...)
React.DOM.p(...)
)
})}
It should now be clear that the second snippet doesn't really make sense (you can't return more than one value in JavaScript). You have to either wrap it in another element (most likely what you'd want, that way you can also provide a valid key
property), or you can use something like this:
{[1,2,3].map(function (n) {
return ([
React.DOM.h3(...),
React.DOM.p(...)
]);
})}
With JSX syntactic sugar:
{[1,2,3].map(function (n) {
return ([
<h3></h3>, // note the comma
<p></p>
]);
})}
You don't need to flatten the resulting array. React will do that for you. See the following fiddle http://jsfiddle.net/mEB2V/1/. Again: Wrapping the two elements into a div/section will most likely be better long term.
score:0
This happens when you are not on the current project, I had three projects in one folder and had this error.
Once switched to a project the issue is gone.
score:1
It is simple by React fragment <></>
and React.Fragment
:
return (
<>
{[1, 2, 3].map(
(n, index): ReactElement => (
<React.Fragment key={index}>
<h3>Item {n}</h3>
<p>Description {n}</p>
</React.Fragment>
),
)}
</>
);
score:2
You can use createFragment
here. See Keyed Fragments.
import createFragment from 'react-addons-create-fragment';
...
{[1,2,3].map((n) => createFragment({
h: <h3>...</h3>,
p: <p>...</p>
})
)}
(I am using ES6 and JSX syntax here.)
You first have to add the react-addons-create-fragment
package:
npm install --save react-addons-create-fragment
The advantage over Jan Olaf Krems's solution: React does not complain about the missing key
.
score:5
Updated
Use React Fragment. It's simple. Link to fragment documentation.
render() {
return (
<>
{[1,2,3].map((value) => <div>{value}</div>)}
</>
);
}
Old answer - obsolete
With React > 16 you can use react-composite.
import { Composite } from 'react-composite';
// ...
{[1,2,3].map((n) => (
<Composite>
<h2>Title {n}</h2>
<p>Description {n}</p>
</Composite>
))};
Of course, react-composite has to be installed.
npm install react-composite --save
score:9
Also, you might want to return several list items in some helper function inside a React component. Just return an array of HTML nodes with the key
attribute:
import React, { Component } from 'react'
class YourComponent extends Component {
// ...
render() {
return (
<ul>
{this.renderListItems()}
</ul>
)
}
renderListItems() {
return [
<li key={1}><a href="#">Link1</a></li>,
<li key={2}><a href="#">Link2</a></li>,
<li key={3} className="active">Active item</li>,
]
}
}
score:16
From React v16.0.0 onwards, it is possible to return multiple elements by wrapping them within an Array
:
render() {
return (
{[1,2,3].map(function (n) {
return [
<h3>Item {n}</h3>.
<p>Description {n}</p>
]
}}
);
}
Also from React v16.2.0, a new feature called React Fragments
is introduced which you can use to wrap multiple elements:
render() {
return (
{[1,2,3].map(function (n, index) {
return (
<React.Fragment key={index}>
<h3>Item {n}</h3>
<p>Description {n}</p>
</React.Fragment>
)
}}
);
}
As per the documentation:
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
Fragments declared with the explicit <React.Fragment> syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:
function Glossary(props) { return ( <dl> {props.items.map(item => ( // Without the `key`, React will fire a key warning <React.Fragment key={item.id}> <dt>{item.term}</dt> <dd>{item.description}</dd> </React.Fragment> ))} </dl> ); }
key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.
score:36
It seems Jan Olaf Krems's answer about returning an array no longer applies (maybe since React ~0.9, as @dogmatic69 wrote in a comment).
The documentation says you need to return a single node:
Maximum Number of JSX Root Nodes
Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.
Don't forget that JSX compiles into regular JS; returning two functions doesn't really make syntactic sense. Likewise, don't put more than one child in a ternary.
In many cases you can simply wrap things in a <div>
or a <span>
.
In my case, I wanted to return multiple <tr>
s. I wrapped them in a <tbody>
– a table is allowed to have multiple bodies.
As of React 16.0, returning an array is apparently allowed again, as long as each element has a key
: New render return types: fragments and strings
React 16.2 lets you surround a list of elements with <Fragment>…</Fragment>
or even <>…</>
, if you prefer that to an array: https://reactjs.org/docs/fragments.html
Source: stackoverflow.com
Related Query
- How can I return multiple lines JSX in another return statement in React?
- { React jsx babel es6 webpack } How Can I Comment in render ( return ( // || /**/ ) )?
- How can I wait for multiple promises to all be done before using their return data for another function call?
- How can I map over and object, that contains another Object I want to map over and return JSX from it?
- React axios api call: How can I return multiple parameters in a url?
- How can I render HTML from another file in a React component?
- How can I add multiple className's to react component?
- Why can I omit the return statement with parenthesis in React
- How to create a privately shared component library which can be used across multiple react projects
- How I can render react components without jsx format?
- How can I use an IIFE in the return function of a react component?
- How to return string or JSX element in TypeScript React component?
- How can I split React Router into multiple files
- React - Material UI Typography how to break long string to multiple lines
- React/webpack - How can I host react app on one server and images/fonts on another server?
- How can I import an existing React component defined in JSX in a Typescript module (.tsx)
- How can I change the default port in react from 3000 to another port?
- How to form a TypeScript rule/config that errors if I don't return a JSX in React Functional Component
- How can I access my react app from another pc in local network?
- In JSX | React How can the prop be passed to the button state so the button state can load a new page?
- React How to return div and variable value for another component
- Return multiple <tr> lines in React
- How can I make a request to an API based on the response from another request? React Hook "useSwr" cannot be called inside a callback
- How can I set react Hooks to another value when it is already set
- How can I access a state value done in react hooks in another js file
- How can I add multiple path for home page with react router dom 6?
- How can I validate an Autocomplete multiple TextField using React Hook Form and Yup?
- How can I return multiple components on App.js file?
- how can i use if inline react jsx
- How can I handle the multiple select box in react in a single state
More Query from same tag
- show messages on the basis of API response in react js
- React Router 4: Pass route props to layout component
- Why does my number seem to be an object in React?
- Bind a function to SVG element
- How to collect data from json file and then add those separetely in a component
- Using express to route external call for Reactjs application
- react download the document in the same page
- Custom sort method for column in ReactTable
- How to export an array of objects that dynmically loaded in react
- How to configure or test a container with redux-mock-store in 2019?
- Change the base color font from stripe CardNumberElement on Material UI
- How to use same component in React multiple time but with different CSS on different pages
- How to display error message correctly from custom hook validation?
- Typescript Routing Error - No overload matches this call
- Swapping HTML element with React.js through props
- Toggle class adding class but not removing it
- Pass down function from parent component to child component is not working
- Integrating React and OpenLayers within a Redux Architecture
- onChange for input React JS makes typing render slow
- ReactJ How to render current listitem's nested array into an select
- I used ityped-npm library and i18next translator. The problem is, I can’t translate the inside of the array. How do I translate words in an array?
- React Architecture: I have a common middle component that needs to render custom child components
- fetch inside reducer is not working if I use too many .thens
- I cant use bootstrap modals in a map function
- 'recipe' is not defined when mapping a array
- Accessing my socket variable outside of useEffect
- Deno Oak Disable Cors
- How to handle errors in the useEffect's skip in react hooks?
- Control width of react-data-table-component columns
- How to change the function call based on value