Gabriel Henrique Gabriel Henrique - 6 months ago 19
React JSX Question

How to change state of many childs in the same time in React

What is the sittuation?

I Have a react component that render a table which users can select any cell they want.

Users can select isolated cells or keep pressed the mouse and select many cells at once.

This is working fine, you can see at:

To do this, i have a component that render a table, and in the render function i have a for inside other for, to create the rows and the column of the table.

Inside the cells i have another react component with a state that marks if it is selected or not. This Component receive the row and the column as properties, this is your id.

var Tabela = React.createClass({
return {mouseDown:false};
handleMouseDown(event) {
this.setState({mouseDown: true});
handleMouseUp(event) {
this.setState({mouseDown: false});
render() {
const list = [];
for (let i = 0; i< 6; i++){
const cubes = [];
for (let j = 0; j< 6; j++){
cubes.push(<td><Cube r={i} c={j} selected={false}
mouseDown={this.state.mouseDown} /> </td>);
list.push(<tr >{cubes}</tr>);
return (
<div className="table" onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp} onMouseLeave={this.handleMouseUp}>

var Cube = React.createClass({
return {selected: this.props.selected};
handleMouseDown(event) {
this.setState({selected: !this.state.selected});
handleMouseEnter(event) {
this.setState({selected: !this.state.selected});
render() {
let cn = "cube";
cn += ((this.state.selected) ? " selected" : "");
return <div className={cn} onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}> {"["+this.props.r+","+ this.props.c +"]"} </div>;
} });

What is the problem?

I have a requisite that when user double click any cell, i have to change the state of selected to true of all the cells in a predefined axis of this cell. Can be horizontal axis, vertical axis or diagonal axis.

Anyone knows how i can find the cells of a predefined axis and change the state of all these cells in the same time?


You should have the Tabela keep the selected state (as an array of array) and pass it to the Cube so the Cube has no state, only props. That way, you can pass a double click handler from the Tabela to the Cube like :

In Tabela:

handleDoubleClick: function (rowIndex, colIndex) {
   var selected = this.state.selected;
   var row = this.state.selected[rowIndex];
   // here i am inversing the row
   for (let r; r < row.length; r++) { 
       row[r] = !row[r]; // inverse state
   this.setState({ selected: selected });

<Cube selected={ this.state.selected[i][j] }  onDoubleClick={ this.handleDoubleClick.bind(null, i, j) }