I want, when I click on an element, a cross appears on this element. But the cross appears on all lines. In the console, I print the coordinates that come into the function, it is clear that they are correct.

Why is this happening and how to fix it?

class App extends React.Component { constructor (props) { super(props); this.state = { data: Array(5).fill(Array(5).fill('О')), }; } onClick = (i, j) => { return () => { let data = this.state.data; console.clear(); console.log(i, j); data[i][j] = 'X'; this.setState({data}); } }; render() { return ( <div className="field"> {this.state.data.map((item, i) => ( <div key={`row-${i}`} className="field__row"> {item.map((item, j) => <div key={`cell-${j}`} onClick={this.onClick(i, j)} className="field__cell">{item}</div>)} </div> ))} </div> ); } } ReactDOM.render(<App />, document.getElementById('root')); 
 .field { font-size: 0; } .field__cell { position: relative; display: table-cell; width: 30px; height: 30px; border: 1px solid black; vertical-align: middle; font-size: 16px; text-align: center; cursor: pointer; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

  • I do not advise using react 15, so it has become outdated for a long time. Use version 16 - Excess Suslik

1 answer 1

Why is this happening

In your external array, the same one-dimensional array is added five times:

 var data = Array(5).fill(Array(5).fill('О')); data[4][1] = "X"; console.log(data[0][1], data[1][1], data[2][1], data[3][1], data[4][1]); 

and how to fix it

That's right:

 var data = (function(){ var result = Array(5).fill({}); result.forEach((item, ind, arr) => arr[ind] = Array(5).fill('О')); return result; })(); data[4][1] = "X"; console.log(data[0][1], data[1][1], data[2][1], data[3][1], data[4][1]); 

Calm, only calm. Try to understand the first sentence of my answer. Here is what you need to change in your code:

 this.state = { data: (function(){ var result = []; for(var i = 0; i < 5; i++) result[i] = Array(5).fill('О'); return result; })() }; 
  • Just what the hell is going on. I take in your example, the 4th element of the array, which is also an array, and then the 1st. Why is this happening? Besides, I do not want to create a new array, because the old values ​​will be ground. I want to change the values ​​of a specific cell of the array, and do not touch the rest. - Igor
  • Fine! Thank you very much! I got it! - Igor
  • @Igor Please. I want to note the high quality of the issue. Therefore, it was nice to answer it. - Igor