I have started learning react but stuck here. i want to print the value in webpage but cant get what method should i put in onChange and please need a explanation also.
class IncrementDecrement extends React.Component {
constructor(props) {
super(props);
this.state = { a: 0 };
this.change = this.onIncreased.bind(this);
this.change = this.onDecreased.bind(this);
}
change(event) {
this.setState({ a: event.target.value });
}
onIncreased() {
this.state.a = this.state.a + 1;
console.log(this.state.a);
}
onDecreased() {
this.state.a = this.state.a - 1;
console.log(this.state.a);
}
render() {
return (
<div>
<input type="number" value={this.state.a} onChange={this.setState} />
<button
onClick={() => {
this.onIncreased();
}}
>
Increment
</button>
<button
onClick={() => {
this.onDecreased();
}}
>
Decrement
</button>
</div>
);
}
}
ReactDOM.render(<IncrementDecrement />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
>Solution :
Make the following changes:
-
Bind the methods correctly in the constructor.
-
Set
onChangetothis.changeand notthis.setState. -
For updating a piece of state use
this.setStateand don’t mutate the state. -
And in the
changemethod, coerce the value of the input to aNumberfor increment and decrement operations to work properly.
class IncrementDecrement extends React.Component {
constructor(props) {
super(props);
this.state = { a: 0 };
this.change = this.change.bind(this);
this.onIncreased = this.onIncreased.bind(this);
this.onDecreased = this.onDecreased.bind(this);
}
change(event) {
this.setState({ a: Number(event.target.value) });
}
onIncreased() {
this.setState({ a: this.state.a + 1 });
}
onDecreased() {
this.setState({ a: this.state.a - 1 });
}
render() {
return (
<div>
<input type="number" value={this.state.a} onChange={this.change} />
<button
onClick={() => {
this.onIncreased();
}}
>
Increment
</button>
<button
onClick={() => {
this.onDecreased();
}}
>
Decrement
</button>
</div>
);
}
}
ReactDOM.render(<IncrementDecrement />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>