0

I'm currently encountering a problem when i'm calling a for loop in a functional/class component in React. For exemple if I want to create a simple function to render multiple td tr in a table React is going to infinite call the function.

class ReserveView extends Component {
  createTable() {
    const table = []

    for (let i = 0; i < 3; i + 1) {
      const children = []
      for (let j = 0; j < 5; j + 1) {
        children.push(<td>{`Column ${j + 1}`}</td>)
      }
      table.push(<tr>{children}</tr>)
    }
    return table
  }

  render() {
    return (
      <div>
        <table>
          {this.createTable()}
        </table>
      </div>
    )
  }

If i console.log(j) the console will output this

I'm using React for a year now and it's the first time I'm having this issue. Thanks a lot for your help

3 Answers 3

3

Oh yeah, your problem lies in the fact that you never increase the i and j loop variant.

you need to do i++ and j++ instead of j + 1 :)

Sign up to request clarification or add additional context in comments.

1 Comment

I've just tried and it works !! thanks a lot :). I guess i'll have to change my linter !
2

Change your +1s to ++

for (let i = 0; i < 3; i++) {
  const children = []
  for (let j = 0; j < 5; j++) {
    children.push(<td>{`Column ${j + 1}`}</td>)
  }
  table.push(<tr>{children}</tr>)
}
return table

Comments

1

The correct answer has been posted above. Just a note that you may try ES6 map() function. It would be very useful when you are coding with React.

  createTable2() {
    const rows = Array(3).fill(null);
    const columns = Array(5).fill(null);
    return rows.map((item, ridx) => (
      <tr>
        {columns.map((item, cidx) => (
          <td>{`Row ${ridx + 1} - Column ${cidx + 1}`}</td>
        ))}
      </tr>
    ));
  }

Check out the demo here: https://codesandbox.io/s/table-demo-fgd9i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.