I am writing a really simple program but I have got a small problem. When I write a new omen in input label, I want to add this to the array that is in state and display whole content of the array in alert box. How can I do it in the easiest way?
class Draw extends React.Component {
state = {
omen: "",
omens: ["first", "second", "third"],
newOmen: "",
};
handleRandomOmen = () => {
const omensArray = this.state.omens;
const randomOmen =
omensArray[Math.floor(Math.random() * omensArray.length)];
this.setState({
omen: randomOmen,
});
};
handleChange = (e) => {
this.setState({
newOmen: e.target.value,
});
};
handleAddOmen = () => {
const test = this.state.omens.push(this.state.newOmen);
console.log(test);
};
render() {
return (
<div className="app">
<button onClick={this.handleRandomOmen}>Show omen</button>
<br />
<input
type="text"
value={this.state.newOmen}
onChange={this.handleChange}
/>
<button onClick={this.handleAddOmen}>Add omen</button>
<h1>{this.state.omen}</h1>
</div>
);
}
}
ReactDOM.render(<Draw />, document.getElementById("root"));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
you always need to update a state with setState
,
adding a new array value with push
will be overriden by the next react cycle.
You can use your the spread syntax to create a new array with the old values your new one:
handleAddOmen = () => {
this.setState({
omens: [
...this.state.omens,
this.state.newOmen
]
});
};