Skip to content
Advertisement

ReactJS OnClick Function that Changes State Not Rerendering

I am trying to create a floodfill visualization that allows the user to enter the grid size and the grid adjusts dynamically however, the grid is composed of buttons that have an onClick function that would then trigger the floodfill. I read up on the setState function and it says its asynchronous which is the reason that it’s not rerendering and that you should use a callback, however I’m not sure how to do that. When I put the recursive functions into the callback, an error occurs.

JavaScript

How I tried to use the callback function:

JavaScript

I also tried this method which worked for small grids but created a maximum stack error for anything larger than a 3×3 grid.

JavaScript

Advertisement

Answer

React detects changes using reference comparison, so you must modify your array in immutable way.

The easiest is to

  • remove setMatrix from the floodFill function
  • add a second Fill function which calls your current fill function.
  • set the Matrix in the new function, creating a new matrix.
  • update the button.onClick handler to use the new function
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement