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

261
Visualizações
REACT onclick change color of div

I am trying to change each div's color onClick. The problem in my code is that all divs change color when one is clicked. Looking for a way to change each one's color individually

Here is my code :

class Main extends React.PureComponent {
state = {
    color: 'blue',
};
onChange = () => {
    this.setState({color: 'red'});
};
render() {
    return (
        <Box sx={SX.root}>
            <Box sx={SX.page}>
                <Box sx={SX.shapeContainer}>
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                </Box>
                <MathGrid sx={SX.math1} />
            </Box>

            <Box sx={SX.header} />
            <Box sx={SX.footer} />
        </Box>
    );
}

output

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

0

You have to create separate component for each div with changeable colour. This way each component will have its own independently managed state. In your example, you share same color state as the rest.

BoxComponent

class BoxComponent extends React.Component {
    state = {
        color: "blue",
    };

    onChange = () => {
        this.setState({ color: "red" });
    };

    render() {
        return (
            <div
                style={{ backgroundColor: this.state.color, width: 20, height: 20, opacity: "50%" }}
                onClick={this.onChange}
            />
        );
    }
}

MainComponent

class Main extends React.PureComponent {
    render() {
        return (
            <Box sx={SX.root}>
                <Box sx={SX.page}>
                    <Box sx={SX.shapeContainer}>
                        <BoxComponent />
                        <BoxComponent />
                    </Box>
                    <MathGrid sx={SX.math1} />
                </Box>

                <Box sx={SX.header} />
                <Box sx={SX.footer} />
            </Box>
        );
    }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Both divs are using the “color” state value. You’ll need to use two separate pieces of state to manage the color of these two divs independently.

You’ll also need to either add another onChange handler, or modify the existing one to accept a color as an argument.

about 4 years ago · Juan Pablo Isaza Relatório

0

You are using the same state for both boxes so when you change your state - its going to change across the whole component. You will need to make separate states for each component. or create a separate component for the box

<div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
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