Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
Why isnt this React variable working in my state object?
class Squares extends React.Component {
    constructor() {
        super();
        this.color = 'blue';
    }

    state = {
        backgroundColor: this.color,
        width: "50px",
        height: "50px"
    };


    render () {

        return (
            <div>
                <div style={this.state}>Hello</div>
                <button>Add Square</button>
                <p>{this.state.backgroundColor}</p>
            </div>
        );
    }


}

this.color is outputting its value, but I cant assign it to this.state.backgroundColor. I eventually want to add a onClick event to the button and when I click it, i want to output a square with the color changed.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The primary issue here is actually just how JS works - any variables defined outside the constructor are initialized before the constructor. For example:

class Squares {
    constructor() {
        this.color = 'blue';
    }

    state = {
        backgroundColor: this.color,
        otherBackgroundColor: 'blue'
    };


    render () {
        console.log(this.state.backgroundColor)
        console.log(this.state.otherBackgroundColor)
    }
}

const s = new Squares();
s.render();

So if you need to access this.color, and you initialize it in the constructor, you need to initialize this.state in your constructor as well.

class Squares {
    constructor() {
        this.color = 'blue';
        this.state = {
            backgroundColor: this.color,
        }
    }

  
    render () {
        console.log(this.state.backgroundColor)
    }
}

const s = new Squares();
s.render();

about 4 years ago · Juan Pablo Isaza Denunciar

0

this.color = 'blue'; is not state managed.

constructor() {
    super();
    this.state = {
        backgroundColor: 'blue',
        width: "50px",
        height: "50px"
    };
  }

this should work and instead of changing color update the value of backgroundColor

about 4 years ago · Juan Pablo Isaza Denunciar

0

Some working code with button to add square and select to change background color of square.

Working codesandbox link - https://codesandbox.io/s/nice-chaplygin-0m87u

import React, { Component } from "react";

class Squares extends Component {
  state = {
    showSquare: false
  };

  handleClick = () => {
    this.setState({
      showSquare: true
    });
  };

  handleChange = ({ target }) => {
    this.setState({
      backgroundColor: target.value
    });
  };

  render() {
    const { backgroundColor, showSquare } = this.state;
    return (
      <div>
        <div style={{ backgroundColor }} className={showSquare && "square"}>
          Hello
        </div>
        <button onClick={this.handleClick}>Add Square</button>
        <select onChange={this.handleChange}>
          <option value="red">red</option>
          <option value="purple">purple</option>
          <option value="green">green</option>
        </select>
      </div>
    );
  }
}

export default Squares;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda