DEV Community

Tri Lam
Tri Lam

Posted on

Is there a way I can use class abstraction to interact with React components?

I have a Maze class, and all of my logic is abstracted inside the class. I looking for ways to react component to re-render every time the data into the class changes.

I simplified everything so you guys can see it easier. When I press flipAll in Maze, I'm trying to make the components Cell to rerender. At the moment it's static.

I understand that a component can only rerender via state or prop change. But doesn't my cell prop is subscribing to data inside the class. Therefore a prop change?

Is there a way I can make it work without forceUpdate?

End goal: I'm trying to do a maze-making generator that can visualize the path/action taken by the algorithm sequentially.

class Maze { constructor(width, height, includesDiagonal = false) { this.grid = this.createGrid(width, height) } flipAll () { for (let i = 0; i < this.grid.length; i++){ for (let j = 0; j < this.grid.length[0]; j++){ this.grid[i][j].flip() } } createGrid(width, height) { const row = i => [...Array(width)].map((ele, j) => new Cell(i, j)) const grid = [...Array(height)].map((ele, i) => row(i)) return grid } } class Cell { constructor() { this.visited = false; } flip() { this.visited = true } } class MazeChaser extends Component { constructor(props) { super(props) this.Maze = new Maze(5,5) } clickTest = () => this.Maze.flipAll() render() { return (<><Grid grid={this.Maze.grid}/></>)} } const Grid = props => { const rows = props.grid.map((row, ind) => ) return ({rows}) } const Row = props => { const cells = props.row.map((cell, ind) => ); return ({cells}) } const Cell = ({visited})=> ({visited})

Top comments (3)

Collapse
 
dance2die profile image
Sung M. Kim

Hi Tri.

Is there a way I can make it work without forceUpdate?

React is "state" driven. When you think of using forceUpdate, you are making changes to internal maze state and trying to re-render the component.

What you have to do is to put maze state in hooks or in state object. Changing the reference of the state should re-render.

Collapse
 
trilamsr profile image
Tri Lam

I'm new to React. Which hook should I be utilizing if I'm doing something Grid-based?

Collapse
 
dance2die profile image
Sung M. Kim

There are two built-in hooks, useState and useReducer.

A Grid-based state using either useState or useReducer (useState internally uses useReducer). .

If you have other states such as loading, score, win/loss to be updated at the same time as the grid-based state changes, you might want to use useReducer, as it lets you update multiple states at once.