function Circle(props) { return(<span className='Circle'>this a circle</span>) } class Lottery extends React.Component{ constructor(props){ super(props); this.state = {}; } render(){ let circles = () => { let circlesrow = []; for (let i;i < this.props.n;i++) { circles.push(<Circle/>) } return (circlesrow); } return( <div> <div> {circles()} </div> </div> ); } } function App() { return ( <div className="App"> <Lottery n={9}/> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> </div> ); } ReactDOM.render( <App />, 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>
i wanted to insert 9 components in Lottery components.but nothing shows up. can someone just explain to me why a relationship like this doesn’t work in React? and what is the wrong practice used here?
Advertisement
Answer
- Init
i
in the for loop with a0
–i = 0
- push the circles into the row –
circlesrow.push(<Circle />)
- Call the function –
{circles()}
function Circle(props) { return(<span className='Circle'>this a circle</span>) } class Lottery extends React.Component{ state = {}; render(){ const circles = () => { const circlesrow = []; for (let i = 0; i < this.props.n; i++) { circlesrow.push(<Circle />) } return circlesrow; } return( <div> <div> {circles()} </div> </div> ); } } function App() { return ( <div className="App"> <Lottery n={9}/> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> </div> ); } ReactDOM.render( <App />, 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>
You can also generate the circles’ array with Array.from()
direcly:
function Circle(props) { return(<span className='Circle'>this a circle</span>) } class Lottery extends React.Component{ state = {}; render(){ const { n } = this.props; return( <div> <div> {Array.from({ length: n }, (_, i) => <Circle key={i} />)} </div> </div> ); } } function App() { return ( <div className="App"> <Lottery n={9}/> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> </div> ); } ReactDOM.render( <App />, 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>