Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!