1

m looping using for in render function its giving syntax error can we not use this way in react following is the code

render(){
    return(
        <table>               
             for(var i=0;i<this.props.TRlength;i++)                  
               <TRcomponent TDlength={this.state.tdLength} />                                                
        </table>
        )
}

error it throws `/src/Table.js Syntax error: D:/my-app1/src/Table.js: Unexpected token (17:50)

           <table>

             for(var i=0;i<this.props.TRlength;i++)//error here
                                              ^

                  <TRcomponent TDlength={this.state.tdLength} />
              `

any help is appreciated

Tested
  • 761
  • 4
  • 16
  • 38
  • 3
    Possible duplicate of [Loop inside React JSX](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) – JJJ Sep 29 '18 at 06:48

2 Answers2

1

React doesn't play well with for loops in the render. You cannot create children for a parent that does not exist yet. You need to create the children first.

This article goes into detail about this issue.

Holly E
  • 563
  • 1
  • 5
  • 15
1

You can store it in a variable and then use it in jsx

render() {
  var rows = [];
  for (var i=0;i<this.props.TRlength;i++) {
     // note: we add 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(<TRcomponent TDlength={this.state.tdLength} key={i} />);
  }
  return < table >{rows}</table>;
}
Umair Farooq
  • 1,763
  • 13
  • 16