javascript - Outputting n instances of a React component -
i want create n
instances of react component.
what terse way give jsx can contain expressions?
i trying following:
<wrapper> {repeat(n)(i => <mycomponent i={i} />} </wrapper> function repeat(n) { return cb => array(n).fill(null).foreach((_, i) => cb(i)); }
you can use javascript als :)
render() { const lst = [1, 2, 3, 4]; return ( <div> {lst.map(itm => <span key={itm}>{itm}</span>)} </div> ); }
if not have key
ready, can use second argument of map callback index in array. more info on mdn.
in specific case not have array number:
render() { var times = []; (let = 0; < 10; i++) { times.push(<mycomponent key={i} i={i} />); } return <wrapper>{times}</wrapper>; }
also check this answer on how use for
loops. it's not quite nice works. believe react team has planned make working arrays in jsx more straight forward.
if have number, , not want use loop, "fake" it, example using string.repeat. not sure if readable though :)
render() { return ( <div> {'a'.repeat(10).split('').map((_, i) => <mycomponent i={i} />} </div> ); }
Comments
Post a Comment