1

I am creating a 3 x 3 table through a simple loop as following:

  React.useEffect(() => {
    const _array = [];
    let i = -1;
    for (let c = 1; c < 4; c++) {
      for (let r = 1; r < 4; r++) {
        i++;
        _array.push(
          <div
            key={`x${c}x${r}`}
            className={`x${c}x${r}`}
            onClick={() => console.log(i)}
          >
            {i}
          </div>
        );
      }
    }
    setArray(_array);
  }, []);

The console.log(i) in each <div> returns 8 although the {i} prints the correct number each time.

How can I code the correct i inside each div using this loop?

To reproduce you can see the full code on CodeSandbox.

3
  • Why do you want to store React components in state? Commented Dec 4, 2020 at 18:33
  • @ZsoltMeszaros I am producing a table of 3x3. Is there any other way I can do it? I don't want to hard code numbers obviously. Commented Dec 4, 2020 at 18:44
  • Just added an answer, I hope it helps. Commented Dec 4, 2020 at 18:46

1 Answer 1

1

You should NOT store React elements in state, only data that can be rendered later.

According to the old React docs, state should only contain the minimal amount of data needed to represent your UI's state. As such, it should not contain React components. Build them in render() based on underlying props and state.

function App() {
  const [array, setArray] = React.useState([]);

  React.useEffect(() => {
    const _array = [];
    let i = -1;
    for (let c = 1; c < 4; c++) {
      for (let r = 1; r < 4; r++) {
        i++;
        _array.push({ id: `x${c}x${r}`, content: i });
      }
    }
    setArray(_array);
  }, []);

  return (
    <div className="containter">
      <div className="game">
        {array.map((item) => (
          <button
            key={item.id}
            className={item.id}
            onClick={() => console.log(item.content)}
          >
            {item.content}
          </button>
        ))}
      </div>
    </div>
  );
}

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

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

2 Comments

Thanks for the explanation. I understand the misuse now.
I'm glad I could help. :)

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.