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>
change this line
<input type="number" value={this.state.a} onChange={this.setState} />
to
<input type="number" value={this.state.a} onChange={this.change} />
this.change is a handler for the onChange event which take the value and updates the state.
Try setting onChange={this.change}. You have this method defined but aren’t using it, instead passing setState as if it were an event handler, which it isn't.
Make the following changes:
Bind the methods correctly in the constructor.
Set onChange to this.change and not this.setState.
For updating a piece of state use this.setState and don't mutate the state.
And in the change method, coerce the value of the input to a Number for 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>