7

I want to write a simple program where using for loop it will print numbers from 0 to 10. I am trying to use a for loop which will print numbers from 0 to 10 and will pass the props to child component. Here is my code:

import React, { Component } from 'react';
class App extends Component {



  render() {

    return(
      <div>
        <p>
        {
          for(var i=0;i<11;i++)
          {
            // var data=i;
            <Print value={i}/>
          }
        }
       </p>
      </div>
    );
  }
}

const Print=(props)=>{
  return(
    <div>
      {props.value}
    </div>
  );
}

export default App;
user11066242
  • 233
  • 5
  • 18

1 Answers1

4

You can push the JSX to an array and render that.

class App extends React.Component {
  render() {
    const result = [];

    for (var i = 0; i < 11; i++) {
      result.push(<Print value={i} key={i} />);
    }

    return <div>{result}</div>;
  }
}

const Print = props => {
  return <div>{props.value}</div>;
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • But when I add new field like a button into the Print component, everything is getting displayed for each item of the array. I mean for every value of an array an item is getting displayed. – user11066242 Feb 22 '19 at 09:15
  • @user11066242 Yes, you create a `Print` component in every iteration in the loop. If you add something to the `Print` component, all of them will get that change. It you just want it once, you can add it in the `App` component instead. – Tholle Feb 22 '19 at 09:17