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.
CodePudding user response:
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();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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();
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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
CodePudding user response:
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;