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

257
Visualizações
How to change the background color of th on click in react js?

I want to change the background color of th when I click on tr. This is my minimal code:

props.params.map((item, i) => {
   return (
        <>
             <tr key={i} onClick={() => attributeClicked(i) } >            
                    <th className={'a'+i}>                    
                         <span>{ item.label }</span>                
                    </th>
             </tr>
        </>
         )
  })


function attributeClicked (i: number) {
    document.getElementsByClassName(`a${i}`)[0].style.backgroundColor = "red!important";
}

However this code is not working. Also when I hover over style it shows the error Property 'style' does not exist on type 'Element'.ts(2339)

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

0

Hello look a this example using ref to access to the element and change the color of the font or whatever you want.

import { createRef } from "react";
export default function App() {
  const renderTh = (data, index, ref) => {
    return (
      <th ref={ref} key={index} onClick={() => redColor(ref)}>
        {data}
      </th>
    );
  };

  const redColor = (ref) => {
    if (!ref.current) return;
    ref.current.style.color = "red";
  };

  const dataSet = ["one", "two", "three"];
  const refArray = [];
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <table>
        <thead>
          {dataSet.map((data, index) => {
            const ref = createRef();
            refArray[index] = ref;
            return renderTh(data, index, ref);
          })}
        </thead>
      </table>
    </div>
  );
}

Edit ref array react

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