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

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -