'Accessing Child Component in GrandParent component
I am building a Search Algorithm Visualizer website.
The order of components is App->Row->Box
Each box component has its own unique id (rowNumber-colNumber) and has its classname set as "Unvisited"
I have an onclick event in App Component which runs BFS
To visualize Bfs,I have to access and change some specific (based on their id) Box Component's classname to "Visited"
How can i achieve it?
These are my components
//APP COMPONENT
import React from "react"
import Row from "./Row"
export const Start = {row:14,col: 18},End = {row:14,col: 35}
export default function App(){
const [grid,setGrid] = React.useState([])
React.useEffect(() => {
for(let i = 1;i<29;i++){
setGrid(prevArray =>prevArray.concat(<Row key = {i} row = {i}/>))
}
},[])
return (
<>
<div className = "Navbar">
<a href ="#" onClick = {Bfs}>Breadth First Search</a>
</div>
{grid}
</>
)
}
//ROW COMPONENT
import React from "react"
import Box from "./Box"
import {Start,End} from "./App"
export default function Row(props){
const row = [];
for(let colNumber = 1;colNumber<54;colNumber++){
row.push(<Box
key = {colNumber}
row = {props.row}
col = {colNumber}
isStart = {props.row == Start.row && colNumber == Start.col}
isEnd = {props.row == End.row && colNumber == End.col}
/>)
}
return (
<div className ="row">
{row}
</div>
)
}
//BOX COMPONENT
import React from "react";
export default function Box({ row, col, isStart, isEnd }) {
return (
<div className="Unvisited" id={`${row}-${col}`}>
{isStart && <img src="./images/start.png"></img>}
{isEnd && <img src="./images/target.png"></img>}
</div>
)
}
Solution 1:[1]
In App component; const grid = []
since you are using grid as a variable, react doesn't care if the grid changes; you have to use useState hook const [grid, setGrid] = useState([])
and usign setGrid you have to update the value of grid.
React will automatically rerender the component once grid is changed using setGrid.
Whenever you need to update some data on page you need to use state in react
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vipul waghmare |
