score:1592
think of it like you're just calling javascript functions. you can't use a for
loop where the arguments to a function call would go:
return tbody(
for (var i = 0; i < numrows; i++) {
objectrow()
}
)
see how the function tbody
is being passed a for
loop as an argument – leading to a syntax error.
but you can make an array, and then pass that in as an argument:
var rows = [];
for (var i = 0; i < numrows; i++) {
rows.push(objectrow());
}
return tbody(rows);
you can basically use the same structure when working with jsx:
var rows = [];
for (var i = 0; i < numrows; i++) {
// note: we are adding a key prop here to allow react to uniquely identify each
// element in this array. see: https://reactjs.org/docs/lists-and-keys.html
rows.push(<objectrow key={i} />);
}
return <tbody>{rows}</tbody>;
incidentally, my javascript example is almost exactly what that example of jsx transforms into. play around with babel repl to get a feel for how jsx works.
score:1
simple way
you can put numrows in state and use map() instead of a for loop:
{this.state.numrows.map((numrows , index) => {
return (
<objectrow
key={index}
/>
score:2
i have seen one person/previous answer use .concat() in an array, but not like this...
i have used concat to add to a string and then just render the jsx content on the element via the jquery selector:
let list = "<div><ul>";
for (let i=0; i<myarray.length; i++) {
list = list.concat(`<li>${myarray[i].valueyouwant}</li>`);
}
list = list.concat("</ul></div>);
$("#myitem").html(list);
score:2
const numrows = [1, 2, 3, 4, 5];
cosnt renderrows = () => {
return numros.map((itm,index) => <td key={index}>{itm}</td>)
}
return <table>
............
<tr>
{renderrows()}
</tr>
</table>
score:2
inside your render or any function and before return, you can use a variable to store jsx elements. just like this -
const tbodycontent = [];
for (let i=0; i < numrows; i++) {
tbodycontent.push(<objectrow/>);
}
use it inside your tbody like this:
<tbody>
{
tbodycontent
}
</tbody>
but i'll prefer map() over this.
score:2
function pricelist({ self }) {
let p = 10000;
let rows = [];
for(let i=0; i<p; i=i+50) {
let r = i + 50;
rows.push(<dropdown.item key={i} onclick={() => self.setstate({ searchprice: `${i}-${r}` })}>{i}-{r} ₺</dropdown.item>);
}
return rows;
}
<pricelist self={this} />
score:2
if you are used to angular and want a more react-like approach:
try using this simple component with auto hashing and optional trackby similar to angular's.
usage:
<for items={items}>
{item => <div>item</div>}
</for>
custom key/trackby:
<for items={items} trackby={'name'}>
{item => <div>item</div>}
</for>
definition:
export default class for<t> extends component<{ items: t[], trackby?: keyof t, children: (item: t) => react.reactelement }, {}> {
render() {
return (
<fragment>
{this.props.items.map((item: any, index) => <fragment key={this.props.trackby ?? item.id ?? index}>{this.props.children(item)}</fragment>)}
</fragment>
);
}
}
react dev tools:
score:2
try this one please
<tbody>
{array.apply(0, array(numrows)).map(function (x, i) {
return <objectrow/>;
})}
</tbody>
or
{[...array(numrows)].map((x, i) =>
<objectrow/>
)}
score:3
you have to write in jsx:
<tbody>
{
objects.map((object, i) => (
<objectrow obj={object} key={i} />
));
}
</tbody>
score:3
<tbody>
numrows.map((row,index) => (
return <objectrow key={index}/>
)
</tbody>
score:3
maybe the standard of today maximum developer, use a structure like this:
let data = [
{
id: 1,
name: "name1"
},
{
id: 2,
name: "name2"
},
{
id: 3,
name: "name3"
},
{
id: 100,
name: "another name"
}
];
export const row = data => {
return (
<tr key={data.id}>
<td>{data.id}</td>
<td>{data.name}</td>
</tr>
);
};
function app() {
return (
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>{data.map(item => row(item))}</tbody>
</table>
);
}
in the jsx, write your javascript action inside html or any code here, {data.map(item => row(item))}
, use single curly braces and inside a map function. get to know more about map.
and also see the following output here.
score:3
there are multiple ways to loop inside jsx
using a for loop
function tablebodyforloop(props) { const rows = []; // create an array to store list of tr for (let i = 0; i < props.people.length; i++) { const person = props.people[i]; // push the tr to array, the key is important rows.push( <tr key={person.id}> <td>{person.id}</td> <td>{person.name}</td> </tr> ); } // return the rows inside the tbody return <tbody>{rows}</tbody>; }
using the es6 array map method
function tablebody(props) { return ( <tbody> {props.people.map(person => ( <tr key={person.id}> <td>{person.id}</td> <td>{person.name}</td> </tr> ))} </tbody> ); }
full example: https://codesandbox.io/s/cocky-meitner-yztif
the following react docs will be helpful
score:3
it's funny how people give "creative" answers using a newer syntax or uncommon ways to create an array. in my experience working with jsx, i have seen these tricks only used by inexperienced react programmers.
the simpler the solution - the better it is for future maintainers. and since react is a web framework, usually this type of (table) data comes from the api. therefore, the simplest and most practical way would be:
const tablerows = [
{id: 1, title: 'row1'},
{id: 2, title: 'row2'},
{id: 3, title: 'row3'}
]; // data from the api (domain-driven names would be better of course)
...
return (
tablerows.map(row => <objectrow key={row.id} {...row} />)
);
score:3
you can only write a javascript expression in a jsx element, so a for loop cannot work. you can convert the element into an array first and use the map
function to render it:
<tbody>
{[...new array(numrows)].map((e) => (
<objectrow/>
))}
</tbody>
score:3
having the jsx content in the map can be clunky syntax. instead you can do this:
const objectrow = ({ ... }) => <tr key={}>...</tr>
const tablebody = ({ objects }) => {
return <tbody>{objects.map(objectrow)}</tbody>;
}
this is shorthand for
{ objects.map(object => objectrow(object))
if objectrow is set up to take the same keys that are in the object
, this will work great.
note - you may need to set the key
prop when the objectrow is rendered. it can't be passed in through the function call.
more notes - i've run into a few places where this technique is a bad idea. for example, it doesn't go through the normal create component path and won't default prop values for example, so do beware. still, it's handy to know about and is useful sometimes.
score:3
use map to looping
array.map(arrayitem => {
return <objectrow arrayitem={arrayitem}/> // pass array item in component
})
score:3
this is what i used in most of my projects up to now:
const length = 5;
...
<tbody>
{array.from({ length }).map((_,i) => (
<objectrow key={i}/>
))}
</tbody>
score:4
return (
<table>
<tbody>
{
numrows.map((item, index) => {
<objectrow data={item} key={index}>
})
}
</tbody>
</table>
);
score:4
if numrows is an array, as the other answers, the best way is the map
method. if it's not and you only access it from jsx, you can also use this es6 method:
<tbody>
{
[...array(numrows).fill(0)].map((value,index)=><objectrow key={index} />)
}
</tbody>
score:4
you'll want to add elements to an array and render the array of elements.
this can help reduce the time required to re-render the component.
here's some rough code that might help:
myclass extends component {
constructor() {
super(props)
this.state = { elements: [] }
}
render() {
return (<tbody>{this.state.elements}<tbody>)
}
add() {
/*
* the line below is a cheap way of adding to an array in the state.
* 1) add <tr> to this.state.elements
* 2) trigger a lifecycle update.
*/
this.setstate({
elements: this.state.elements.concat([<tr key={elements.length}><td>element</td></tr>])
})
}
}
score:4
i've found one more solution to follow the map render:
<tbody>{this.getcontent()}</tbody>
and a separate function:
getcontent() {
const bodyarea = this.state.movies.map(movies => (
<tr key={movies._id}>
<td>{movies.title}</td>
<td>{movies.genre.name}</td>
<td>{movies.numberinstock}</td>
<td>{movies.publishdate}</td>
<td>
<button
onclick={this.deletmovie.bind(this, movies._id)}
classname="btn btn-danger"
>
delete
</button>
</td>
</tr>
));
return bodyarea;
}
this example solves many problems easily.
score:4
use {}
around javascript code within a jsx block to get it to properly perform whatever javascript action you are trying to do.
<tr>
<td>
{data.map((item, index) => {
{item}
})}
</td>
</tr>
this is kind of vague, but you can swap out data for any array. this will give you a table row and table item for each item. if you have more than just one thing in each node of the array, you will want to target that specifically by doing something like this:
<td>{item.someproperty}</td>
in which case, you will want to surround it with a different td
and arrange the previous example differently.
score:4
there are many solutions posted out there in terms of iterating an array and generating jsx elements. all of them are good, but all of them used an index directly in a loop. we are recommended to use unique id from data as a key, but when we do not have a unique id from each object in the array we will use index as a key, but you are not recommended to use an index as a key directly.
one more thing why we go for .map, but why not .foeach because .map returns a new array. there are different ways of doing .map these days.
below different versions of using .map illustrates in detail about how to use a unique key and how to use .map for looping jsx elements.
.map without return when returning single a jsx element and unique id from data as a key version:
const {objects} = this.state;
<tbody>
{objects.map(object => <objectrow obj={object} key={object.id} />)}
</tbody>
.map without return when returning multiple jsx elements and unique id from data as a key version
const {objects} = this.state;
<tbody>
{objects.map(object => (
<div key={object.id}>
<objectrow obj={object} />
</div>
))}
</tbody>
.map without return when returning a single jsx element and index as a key version:
const {objects} = this.state;
<tbody>
{objects.map((object, index) => <objectrow obj={object} key={`key${index}`} />)}
</tbody>
.map without return when returning multiple jsx elements and index as a key version:
const {objects} = this.state;
<tbody>
{objects.map((object, index) => (
<div key={`key${index}`}>
<objectrow obj={object} />
</div>
))}
</tbody>
.map with return when returning multiple jsx elements and index as a key version:
const {objects} = this.state;
<tbody>
{objects.map((object, index) => {
return (
<div key={`key${index}`}>
<objectrow obj={object} />
</div>
)
})}
</tbody>
.map with return when returning multiple jsx elements and unique id from data as a key version:
const {objects} = this.state;
<tbody>
{objects.map(object => {
return (
<div key={object.id}>
<objectrow obj={object} />
</div>
)
})}
</tbody>
the other way is
render() {
const {objects} = this.state;
const objectitems = objects.map(object => {
return (
<div key={object.id}>
<objectrow obj={object} />
</div>
)
})
return(
<div>
<tbody>
{objectitems}
</tbody>
</div>
)
}
score:4
to provide a more straightforward solution in case you want to use a specific row count which is stored as integer
-value.
with the help of typedarrays
we could achieve the desired solution in the following manner.
// let's create a typedarray with length of `numrows`-value
const typedarray = new int8array(numrows); // typedarray.length is now 2
const rows = []; // prepare rows-array
for (let arrkey in typedarray) { // iterate keys of typedarray
rows.push(<objectrow key={arrkey} />); // push to an rows-array
}
// return rows
return <tbody>{rows}</tbody>;
score:4
render() {
const elements = ['one', 'two', 'three'];
const items = []
for (const [index, value] of elements.entries()) {
items.push(<li key={index}>{value}</li>)
}
return (
<div>
{items}
</div>
)
}
score:5
you can use an iife if you really want to literally use a for loop inside jsx.
<tbody>
{
(function () {
const view = [];
for (let i = 0; i < numrows; i++) {
view.push(<objectrow key={i}/>);
}
return view;
}())
}
</tbody>
score:5
@jacefarm if i understand right you can use this code:
<tbody>
{ new array(numrows).fill(<objectrow/>) }
</tbody>
either you can use this code:
<tbody>
{ new array(numrows).fill('').map((item, ind) => <objectrow key={ind}/>) }
</tbody>
and this:
<tbody>
new array(numrows).fill(objectrow).map((item, ind) => <item key={ind}/>)
</tbody>
score:5
using map in react are best practices for iterating over an array.
to prevent some errors with es6, the syntax map is used like this in react:
<tbody>
{items.map((item, index) => <objectrow key={index} name={item.name} />)}
</tbody>
here you call a component, <objectrow/>, so you don't need to put parenthesis after the arrow.
but you can be make this too:
{items.map((item, index) => (
<objectrow key={index} name={item.name} />
))}
or:
{items.map((item, index) => {
// here you can log 'item'
return (
<objectrow key={index} name={item.name} />
)
})}
i say that because if you put a bracket "{}" after the arrow react will not throw an error and will display a whitelist.
score:5
the problem is you don't return any jsx element. there are another solutions for such cases, but i will provide the simplest one: "use the map function"!
<tbody>
{ numrows.map(item => <objectrow key={item.uniquefield} />) }
</tbody>
it's so simple and beautiful, isn't it?
score:5
you can create a new component like below:
pass key and data to your objectrow
component like this:
export const objectrow = ({key,data}) => {
return (
<div>
...
</div>
);
}
create a new component objectrowlist
to act like a container for your data:
export const objectrowlist = (objectrows) => {
return (
<tbody>
{objectrows.map((row, index) => (
<objectrow key={index} data={row} />
))}
</tbody>
);
}
score:5
i am not sure if this will work for your situation, but often [map][1] is a good answer.
if this was your code with the for
loop:
<tbody>
for (var i=0; i < objects.length; i++) {
<objectrow obj={objects[i]} key={i}>
}
</tbody>
you could write it like this with the map
function:
<tbody>
{objects.map(function(object, i){
return <objectrow obj={object} key={i} />;
})}
</tbody>
objects.map
is the best way to do a loop, and objects.filter
is the best way to filter the required data. the filtered data will form a new array, and objects.some
is the best way to check whether the array satisfies the given condition (it returns boolean).
score:5
you could do the following to repeat a component numrows
times
<tbody>{array(numrows).fill(<objectrow />)}</tbody>
score:6
well, here you go.
{
[1, 2, 3, 4, 5, 6].map((value, index) => {
return <div key={index}>{value}</div>
})
}
all you have to do is just map your array and return whatever you want to render. and please don't forget to use key
in the returned element.
score:6
you can do the same directly in the jsx, using map instead of a for-of loop:
render: function() {
const items = ['one', 'two', 'three'];
return (
<ul>
{items.map((value, index) => {
return <li key={index}>{value}</li>
})}
</ul>
)
}
score:6
try this
<tbody>
{new array(numrows).map((row,index)=><objectrow key={***somethinguniqe***}/>)} //don't use index as key
</tbody>
if you wanna know why you shouldn't use indices as keys in react check this
score:7
react elements are simple javascript, so you can follow the rule of javascript. you can use a for
loop in javascript like this:-
<tbody>
for (var i=0; i < numrows; i++) {
<objectrow/>
}
</tbody>
but the valid and best way is to use the .map
function. shown below:-
<tbody>
{listobject.map(function(listobject, i){
return <objectrow key={i} />;
})}
</tbody>
here, one thing is necessary: to define the key. otherwise it will throw a warning like this:-
warning.js:36 warning: each child in an array or iterator should have a unique "key" prop. check the render method of
componentname
. see "link" for more information.
score:7
for printing an array value if you don't have the key value par, then use the below code -
<div>
{my_arr.map(item => <div>{item} </div> )}
</div>
score:7
you can try the new for of loop:
const apple = {
color: 'red',
size: 'medium',
weight: 12,
sugar: 10
}
for (const prop of apple.entries()){
console.log(prop);
}
here's a few examples:
score:7
unless you declare a function and enclose it with parameters, it is not possible. in a jsxexpression you can only write expressions and cannot write statements like a for(), declare variables or classes, or a if() statement.
that's why function callexpressions are so in the mood today. my advice: get used to them. this is what i would do:
const names = ['foo', 'bar', 'seba']
const people = <ul>{names.map(name => <li>{name}</li>)}</ul>
filtering:
const names = ['foo', undefined, 'seba']
const people = <ul>{names.filter(person => !!person).map(name => <li>{name}</li>)}</ul>
if():
var names = getnames()
const people = {names && names.length &&
<ul>{names.map(name => <li>{name}</li>)}</ul> }
if - else:
var names = getnames()
const people = {names && names.length ?
<ul>{names.map(name => <li>{name}</li>)}</ul> : <p>no results</p> }
score:7
use the map function.
<tbody>
{objects.map((object, i) => <objectrow obj={object} key={i} />)}
</tbody>
score:7
just do something like this:
<tbody>
{new array(numrows).fill("", 0, numrows).map((p, i) => <yourraw key={i} />)}
</tbody>
score:8
you can do something like:
let foo = [1,undefined,3]
{ foo.map(e => !!e ? <object /> : null )}
score:8
if you need javascript code inside your jsx, you add { }
and then write your javascript code inside these brackets.
it is just that simple.
and the same way you can loop inside jsx/react.
say:
<tbody>
{`your piece of code in javascript` }
</tbody>
example:
<tbody>
{ items.map((item, index) => {
console.log(item)}) ; // print item
return <span>{index}</span>;
} // looping using map()
</tbody>
score:8
below are possible solutions that you can do in react in terms of iterating array of objects or plain array
const rows = [];
const numrows = [{"id" : 01, "name" : "abc"}];
numrows.map((data, i) => {
rows.push(<objectrow key={data.id} name={data.name}/>);
});
<tbody>
{ rows }
</tbody>
or
const rows = [];
const numrows = [1,2,3,4,5];
for(let i=1, i <= numrows.length; i++){
rows.push(<objectrow key={numrows[i]} />);
};
<tbody>
{ rows }
</tbody>
an even more better approach i became familiar with recent days for iterating an array of objects is .map
directly in the render with return or without return:
.map with return
const numrows = [{"id" : 01, "name" : "abc"}];
<tbody>
{numrows.map(data=> {
return <objectrow key={data.id} name={data.name}/>
})}
</tbody>
.map without return
const numrows = [{"id" : 01, "name" : "abc"}];
<tbody>
{numrows.map(data=> (
<objectrow key={data.id} name={data.name}/>
))}
</tbody>
score:8
array.from is the best way. if you want to create an array of jsx with some length.
function app() {
return (
<tbody>
{array.from({ length: 10 }, (_, key) => (
<objectrow {...{ key }} />
))}
</tbody>
);
}
the above example is for when you do not have an array, so if you have an array you should map it in jsx like this:
function app() {
return (
<tbody>
{list.map((item, key) => (
<objectrow {...{ key }} />
))}
</tbody>
);
}
score:9
when i want to add a certain number of components, i use a helper function.
define a function that returns jsx:
const myexample = () => {
let myarray = []
for(let i = 0; i<5;i++) {
myarray.push(<mycomponent/>)
}
return myarray
}
//... in jsx
<tbody>
{myexample()}
</tbody>
score:9
a loop inside jsx is very simple. try this:
return this.state.data.map((item, index) => (
<componentname key={index} data={item} />
));
score:9
even this piece of code does the same job.
<tbody>
{array.map(i =>
<objectrow key={i.id} name={i.name} />
)}
</tbody>
score:9
with time, the language is becoming more mature, and we often stumble upon common problems like this. the problem is to loop a component 'n' times.
{[...new array(n)].map((item, index) => <mycomponent key={index} />)}
where, n -is the number of times you want to loop. item
will be undefined and index
will be as usual. also, eslint discourages using an array index as key.
but you have the advantage of not requiring to initialize the array before and most importantly avoiding the for
loop...
to avoid the inconvenience of item as undefined you can use an _
, so that it will be ignored when linting and won't throw any linting error, such as
{[...new array(n)].map((_, index) => <mycomponent key={index} />)}
score:10
you can also use a self-invoking function:
return <tbody>
{(() => {
let row = []
for (var i = 0; i < numrows; i++) {
row.push(<objectrow key={i} />)
}
return row
})()}
</tbody>
score:10
if you really want a for loop equivalent (you have a single number, not an array), just use range
from lodash.
don't reinvent the wheel and don't obfuscate your code. just use the standard utility library.
import range from 'lodash/range'
range(4);
// => [0, 1, 2, 3]
range(1, 5);
// => [1, 2, 3, 4]
score:11
i use it like
<tbody>
{ numrows ? (
numrows.map(obj => { return <objectrow /> })
) : null
}
</tbody>
score:13
since you are writing javascript syntax inside jsx code, you need to wrap your javascript code in curly braces.
row = () => {
var rows = [];
for (let i = 0; i<numrows; i++) {
rows.push(<objectrow/>);
}
return rows;
}
<tbody>
{this.row()}
</tbody>
score:14
here is a sample from the react documentation, javascript expressions as children:
function item(props) {
return <li>{props.message}</li>;
}
function todolist() {
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
return (
<ul>
{todos.map((message) => <item key={message} message={message} />)}
</ul>
);
}
as for your case, i suggest writing like this:
function render() {
return (
<tbody>
{numrows.map((roe, index) => <objectrow key={index} />)}
</tbody>
);
}
please notice the key is very important, because react use the key to differ data in array.
score:15
you may use .map() in a react for loop.
<tbody>
{ newarray.map(() => <objectrow />) }
</tbody>
score:16
your jsx code will compile into pure javascript code, any tags will be replaced by reactelement
objects. in javascript, you cannot call a function multiple times to collect their returned variables.
it is illegal, the only way is to use an array to store the function returned variables.
or you can use array.prototype.map
which is available since javascript es5 to handle this situation.
maybe we can write other compiler to recreate a new jsx syntax to implement a repeat function just like angular's ng-repeat
.
score:16
i tend to favor an approach where programming logic happens outside the return value of render
. this helps keep what is actually rendered easy to grok.
so i'd probably do something like:
import _ from 'lodash';
...
const tablebody = ({ objects }) => {
const objectrows = objects.map(obj => <objectrow object={obj} />);
return <tbody>{objectrows}</tbody>;
}
admittedly this is such a small amount of code that inlining it might work fine.
score:17
you can of course solve with a .map as suggested by the other answer. if you already use babel, you could think about using jsx-control-statements.
they require a little of setting, but i think it's worth in terms of readability (especially for non-react developer). if you use a linter, there's also eslint-plugin-jsx-control-statements.
score:17
here's a simple solution to it.
var object_rows = [];
for (var i = 0; i < numrows; i++) {
object_rows.push(<objectrow />);
}
<tbody>{object_rows}</tbody>;
no mapping and complex code is required. you just need to push the rows to the array and return the values to render it.
score:17
simply use .map()
to loop through your collection and return <objectrow>
items with props from each iteration.
assuming objects
is an array somewhere...
<tbody>
{ objects.map((obj, index) => <objectrow obj={ obj } key={ index }/> ) }
</tbody>
score:20
...or you can also prepare an array of objects and map it to a function to have the desired output. i prefer this, because it helps me to maintain the good practice of coding with no logic inside the return of render.
render() {
const mapitem = [];
for(let i =0;i<item.length;i++)
mapitem.push(i);
const singleitem => (item, index) {
// item the single item in the array
// the index of the item in the array
// can implement any logic here
return (
<objectrow/>
)
}
return(
<tbody>{mapitem.map(singleitem)}</tbody>
)
}
score:20
i use this:
griditems = this.state.applications.map(app =>
<applicationitem key={app.id} app={app } />
);
ps: never forget the key or you will have a lot of warnings!
score:20
es2015 array.from with the map function + key
if you have nothing to .map()
you can use array.from()
with the map
function to repeat elements:
<tbody>
{array.from({ length: 5 }, (value, key) => <objectrow key={key} />)}
</tbody>
score:21
this can be done in multple ways.
as suggested above, before
return
store all elements in the arrayloop inside
return
method 1 let container = []; let arr = [1, 2, 3] //can be anything array, object
arr.foreach((val, index) => { container.push( <div key={index}> val </div>) /** * 1. all loop generated elements require a key * 2. only one parent element can be placed in array * e.g. container.push( * <div key={index}> val </div> <div> this will throw error </div> ) **/ }); return ( <div> <div>any things goes here</div> <div>{container}</div> </div> )
method 2
return ( <div> <div>any things goes here</div> <div> { (() => { let container = []; let arr = [1, 2, 3] //can be anything array, object arr.foreach((val, index) => { container.push( <div key={index}> val </div>) }); return container; })() } </div> </div> )
score:27
an ecmascript 2015 / babel possibility is using a generator function to create an array of jsx:
function* jsxloop(times, callback)
{
for(var i = 0; i < times; ++i)
yield callback(i);
}
...
<tbody>
{[...jsxloop(numrows, i =>
<objectrow key={i}/>
)]}
</tbody>
score:29
to loop for a number of times and return, you can achieve it with the help of from
and map
:
<tbody>
{
array.from(array(i)).map(() => <objectrow />)
}
</tbody>
where i = number of times
if you want to assign unique key ids into the rendered components, you can use react.children.toarray
as proposed in the react documentation
react.children.toarray
returns the children opaque data structure as a flat array with keys assigned to each child. useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
note:
react.children.toarray()
changes keys to preserve the semantics of nested arrays when flattening lists of children. that is, toarray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.
<tbody>
{
react.children.toarray(
array.from(array(i)).map(() => <objectrow />)
)
}
</tbody>
score:30
let us say we have an array of items in your state:
[{name: "item1", id: 1}, {name: "item2", id: 2}, {name: "item3", id: 3}]
<tbody>
{this.state.items.map((item) => {
<objectrow key={item.id} name={item.name} />
})}
</tbody>
score:31
there are several answers pointing to using the map
statement. here is a complete example using an iterator within the featurelist component to list feature components based on a json data structure called features.
const featurelist = ({ features, onclickfeature, onclicklikes }) => (
<div classname="feature-list">
{features.map(feature =>
<feature
key={feature.id}
{...feature}
onclickfeature={() => onclickfeature(feature.id)}
onclicklikes={() => onclicklikes(feature.id)}
/>
)}
</div>
);
you can view the complete featurelist code on github. the features fixture is listed here.
score:36
if numrows is an array, it's very simple:
<tbody>
{numrows.map(item => <objectrow />)}
</tbody>
the array data type in react is much better. an array can back a new array, and support filter, reduce, etc.
score:41
if you opt to convert this inside return() of the render method, the easiest option would be using the map( ) method. map your array into jsx syntax using the map() function, as shown below (es6 syntax is used).
inside the parent component:
<tbody>
{ objectarray.map(object => <objectrow key={object.id} object={object.value} />) }
</tbody>
please note the key
attribute is added to your child component. if you didn't provide a key attribute, you can see the following warning on your console.
warning: each child in an array or iterator should have a unique "key" prop.
note: one common mistake people do is using index
as the key when iterating. using index
of the element as a key is an antipattern, and you can read more about it here. in short, if it's not a static list, never use index
as the key.
now at the objectrow component, you can access the object from its properties.
inside the objectrow component
const { object } = this.props
or
const object = this.props.object
this should fetch you the object you passed from the parent component to the variable object
in the objectrow component. now you can spit out the values in that object according to your purpose.
references:
score:46
you might want to checkout react templates, which does let you use jsx-style templates in react, with a few directives (such as rt-repeat).
your example, if you used react-templates, would be:
<tbody>
<objectrow rt-repeat="obj in objects"/>
</tbody>
score:56
you can also extract outside the return block:
render: function() {
var rows = [];
for (var i = 0; i < numrows; i++) {
rows.push(<objectrow key={i}/>);
}
return (<tbody>{rows}</tbody>);
}
score:65
there are multiple ways to go about doing this. jsx eventually gets compiled to javascript, so as long as you're writing valid javascript, you'll be good.
my answer aims to consolidate all the wonderful ways already presented here:
if you do not have an array of object, simply the number of rows:
within the return
block, creating an array
and using array.prototype.map
:
render() {
return (
<tbody>
{array(numrows).fill(null).map((value, index) => (
<objectrow key={index}>
))}
</tbody>
);
}
outside the return
block, simply use a normal javascript for loop:
render() {
let rows = [];
for (let i = 0; i < numrows; i++) {
rows.push(<objectrow key={i}/>);
}
return (
<tbody>{rows}</tbody>
);
}
immediately invoked function expression:
render() {
return (
<tbody>
{() => {
let rows = [];
for (let i = 0; i < numrows; i++) {
rows.push(<objectrow key={i}/>);
}
return rows;
}}
</tbody>
);
}
if you have an array of objects
within the return
block, .map()
each object to a <objectrow>
component:
render() {
return (
<tbody>
{objectrows.map((row, index) => (
<objectrow key={index} data={row} />
))}
</tbody>
);
}
outside the return
block, simply use a normal javascript for loop:
render() {
let rows = [];
for (let i = 0; i < objectrows.length; i++) {
rows.push(<objectrow key={i} data={objectrows[i]} />);
}
return (
<tbody>{rows}</tbody>
);
}
immediately invoked function expression:
render() {
return (
<tbody>
{(() => {
const rows = [];
for (let i = 0; i < objectrows.length; i++) {
rows.push(<objectrow key={i} data={objectrows[i]} />);
}
return rows;
})()}
</tbody>
);
}
score:83
if you're already using lodash
, the _.times
function is handy.
import react, { component } from "react";
import select from "./select";
import _ from "lodash";
export default class app extends component {
render() {
return (
<div classname="container">
<ol>
{_.times(3, (i) => (
<li key={i}>repeated 3 times</li>
))}
</ol>
</div>
);
}
}
score:106
using the array map function is a very common way to loop through an array of elements and create components according to them in react. this is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in jsx. it's not the only way to do it, but the preferred way.
also, don't forget having a unique key for each iteration as required. the map function creates a unique index from 0, but it's not recommended using the produced index, but if your value is unique or if there is a unique key, you can use them:
<tbody>
{numrows.map(x=> <objectrow key={x.id} />)}
</tbody>
also, a few lines from mdn if you not familiar with the map function on array:
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. it is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed.
if a thisarg parameter is provided to the map, it will be used as callback's this value. otherwise, the value undefined will be used as its this value. this value ultimately observable by the callback is determined according to the usual rules for determining the this seen by a function.
map does not mutate the array on which it is called (although callback, if invoked, may do so).
score:123
simply using map array method with es6 syntax:
<tbody>
{items.map(item => <objectrow key={item.id} name={item.name} />)}
</tbody>
don't forget the key
property.
score:613
if you don't already have an array to map()
like @fakerainbrigand's answer, and want to inline this so the source layout corresponds to the output closer than @sophiealpert's answer:
with es2015 (es6) syntax (spread and arrow functions)
http://plnkr.co/edit/mfqfwodvy8dkqqokiegv?p=preview
<tbody>
{[...array(10)].map((x, i) =>
<objectrow key={i} />
)}
</tbody>
re: transpiling with babel, its caveats page says that array.from
is required for spread, but at present (v5.8.23
) that does not seem to be the case when spreading an actual array
. i have a documentation issue open to clarify that. but use at your own risk or polyfill.
vanilla es5
array.apply
<tbody>
{array.apply(0, array(10)).map(function (x, i) {
return <objectrow key={i} />;
})}
</tbody>
inline iife
http://plnkr.co/edit/4kqjdtzd4w69g8suu2ht?p=preview
<tbody>
{(function (rows, i, len) {
while (++i <= len) {
rows.push(<objectrow key={i} />)
}
return rows;
})([], 0, 10)}
</tbody>
combination of techniques from other answers
keep the source layout corresponding to the output, but make the inlined part more compact:
render: function () {
var rows = [], i = 0, len = 10;
while (++i <= len) rows.push(i);
return (
<tbody>
{rows.map(function (i) {
return <objectrow key={i} index={i} />;
})}
</tbody>
);
}
with es2015 syntax & array
methods
with array.prototype.fill
you could do this as an alternative to using spread as illustrated above:
<tbody>
{array(10).fill(1).map((el, i) =>
<objectrow key={i} />
)}
</tbody>
(i think you could actually omit any argument to fill()
, but i'm not 100% on that.) thanks to @fakerainbrigand for correcting my mistake in an earlier version of the fill()
solution (see revisions).
key
in all cases the key
attr alleviates a warning with the development build, but isn't accessible in the child. you can pass an extra attr if you want the index available in the child. see lists and keys for discussion.
score:1045
i am not sure if this will work for your situation, but often map is a good answer.
if this was your code with the for loop:
<tbody>
for (var i=0; i < objects.length; i++) {
<objectrow obj={objects[i]} key={i}>
}
</tbody>
you could write it like this with map:
<tbody>
{objects.map(function(object, i){
return <objectrow obj={object} key={i} />;
})}
</tbody>
es6 syntax:
<tbody>
{objects.map((object, i) => <objectrow obj={object} key={i} />)}
</tbody>
Source: stackoverflow.com
Related Query
- Loop inside React JSX
- How to loop over a number in React inside JSX
- How to loop inside map function using jsx format React JS
- How to eliminate empty node with loop inside React JSX
- Access props inside quotes in React JSX
- Adding a new line in a JSX string inside a paragraph - React
- React hooks useCallback with parameters inside loop
- Different ways to add a key to JSX element in loop in React
- Use For loop inside JSX
- How to Separate Jsx inside render function into a separate file in ES6? or any other solution in react to separate the Logic and presentation?
- React (typescript): How to loop inside const creation
- Adding a key-value pair to an object inside loop using React useState hook
- How to loop through objects in JSX react
- React JS printing data inside a nested map function in JSX
- How to loop through properties of objects inside of an array within a React component?
- Module parse failed: es6 react component with JSX inside .JS file
- React unnecessary rerender inside .map loop
- loops inside jsx in react
- React is rendering [Object object] instead of JSX elements inside the array
- Can't using block inside return() React JSX
- Can I use a loop inside a react hook?
- onClick inside mapped object JSX for React NextJS not working
- How to handle promises inside the JSX in React JS?
- How to loop inside a react const variable in the render method
- React JSX: href path inside an array of anchor tags is referencing the last path in a loop
- setState inside a loop - React
- React lazy import doesn't work when using inside for loop
- How to prevent infinite loop in my React code when using setState inside useEffect
- Async function inside for loop in React
- Multiple function calls inside curly braces in React JSX
More Query from same tag
- Material UI v5 - Tabs style override
- Server is responding with unwanted response?
- React Navigation weird back button behavior in nested navigators
- how to fetch data from back-end
- Construct React Component from a React Element
- How to Implement Multi Select Dropdown in React
- Call API from React
- Translating DropTarget decorator to ES6
- Material-ui: Warning: Unknown event handler property `onKeyboardFocus`. It will be ignored
- Calling React JS from jsp
- How to run material UI example snippets within a component
- CSSTransition nodeRef for component with direct children
- Using Netlify lambda functions to send emails from a GatsbyJS site
- Next.JS: How to handle error in getInitialProps?
- Flexbox - Set flex item size based total number of items
- props.match.params.id works when I am testing but does not when I deploy in github with gh-pages
- React Router wildcard paths on root directory
- Is it good practice to add a condition in a state definition?
- React Firebase - Fetching an item by id
- How do I call a function present in a javascript file once the React component is loaded?
- React context returns undefined on first login, but works on page refresh
- How should I pass my prop to get a valid Array[Object]
- In React, how can a parent change prop or state values on another component programatically?
- How to prevent getServerSideProps from running again when pushing query param?
- Mount does not work in enzyme with next js
- Convert document.querySelector() into Reactjs
- How do i fix items not being shown on screen from mongo db?
- react native navigator best way to model in a large app?
- How to upload multiple file with react/node and multer
- How use react-rails with webpacker?