0

I am trying to access and set state of multiple child components from the parent component. So far i have tried useRef but the reference is not updated when the actual component changes state(by itself). I tried moving states one level up(into the parent) but that does not make sense to me. These are the 2 components.

function GameGrid() {
  // PARENT COMPONENT
  const classes = useStyles();
  const n = 10;
  let cells = new Array(n).fill(new Array(n).fill(<Cell />));
  const handler = () => {
    cells.map((item) => item.map(subItem => 
        //Access state of each item in 2d array
    ));
  };
  return (
    <Box
      className={classes.grid}
      sx={{ gridTemplateColumns: `repeat(${n}, 1fr)` }}
      onClick={handler}
    >
      {cells.map((item, i) => item.map((subItem, j) => subItem))}
    </Box>
  );
}

export default class Cell extends Component {
  //CHILD COMPONENT
  constructor(props) {
    super(props);
    this.state = { active: false };
    this.classList = 'cell';
  }
  render() {
    return (
      <div
        className={this.state.active ? 'cell activeCell' : 'cell inactiveCell'}
        onClick={() => this.setState({ active: !this.state.active })}
      ></div>
    );
  }
}
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29

0 Answers0