Entonces, estoy tratando de crear un visualizador de algoritmos de clasificación y me encontré con un problema en el que quiero actualizar cada div que se ha incluido en la lista con una nueva altura aleatoria.
import React, { useState, useRef } from 'react' import "../styling/Sorting.css"; import Slider from '@material-ui/core/Slider'; function Sorting() { const [value, setValue] = useState(0); const changeValue = (event, newValue) => { setValue(newValue) } const barRef = useRef() function randomHeight(){ var number1 = Math.floor(Math.random(10) * 500); barRef.current.style.height = number1 + "px"; } return ( <div className="container"> <nav> <div className="slider"> <Slider value={value} onChange={changeValue} max={30} valueLabelDisplay="on"/> </div> <div className="random_height"> <button onClick={randomHeight}>random</button> </div> </nav> <div className="bars"> {Array.from({ length: value }, (_, i) => <div className="bar" id="bar" ref={barRef} key={i}></div> )} </div> </div> ) } export default SortingSin embargo, solo puedo cambiar el div actual, que es el último div que se agregó a la matriz.
Necesita administrar múltiples referencias, por ejemplo:
import React, { useState, useRef } from "react"; import "../styling/Sorting.css"; import Slider from "@material-ui/core/Slider"; function Sorting() { const [value, setValue] = useState(0); const changeValue = (event, newValue) => { setValue(newValue); }; const barRef = useRef([]); function randomHeight() { barRef.current.forEeach((node) => { const number1 = Math.floor(Math.random(10) * 500); node.style.height = number1 + "px"; }); } return ( <div className="container"> <nav> <div className="slider"> <Slider value={value} onChange={changeValue} max={30} valueLabelDisplay="on" /> </div> <div className="random_height"> <button onClick={randomHeight}>random</button> </div> </nav> <div className="bars"> {Array.from({ length: value }, (_, i) => ( <div className="bar" id="bar" ref={(node) => (ref.current[i] = node)} key={i} ></div> ))} </div> </div> ); } export default Sorting;