Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
How to change style of element using ref in react js

So i'm trying to create a sorting algorithms visualiser and i've come across a problem where i want to update each div that's been looped into the list with a new random height.

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 Sorting

However I'm only able to change the current div which is the last div that's been added to the array.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to manage multiple refs, for example:

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;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda