Reputation: 841
I have an input number value which I'm trying to send to my clickHandler but I've done something wrong ...
On click I want to send the value "this.state.NumberHolder" to the handler
<input value={this.state.NumberHolder} onClick={this.clickHandler} type="number" />
Doing a console.log I can see that my clickHandler is being called but I'm not getting the updated state value
clickHandler = (target) => {
console.log("targetHere", target);
this.setState({
NumberHolder: target.value
});
};
Upvotes: 2
Views: 512
Reputation: 2077
Actually, what you receive by default property is the context of the event.
So, to handle correctly the value of the input tag, you need to do this:
clickHandler = (event) => {
console.log("targetHere", event.target);
this.setState({
NumberHolder: event.target.value
});
};
And there is a big issue with your JSX, onClick
is executed when the input is clicked, not changed. So, you will never receive the new input value. Use on change:
<input value={this.state.NumberHolder} onChange={this.clickHandler} type="number" />
And this should work perfectly. Check this fiddle to see it working.
Upvotes: 1
Reputation: 810
Considering your comments, i believe you want to add the event on change of the input
and log the value entered like this:
<input value={this.state.NumberHolder} onChange={this.clickHandler} type="number" />
clickHandler = (target) => {
console.log("target Value", target.value);
this.setState({
NumberHolder: target.value
});
};
Upvotes: 0
Reputation: 495
I believe it should be like this:
// destructure target from the event object by wrapping it in braces
clickHandler = ({target}) => {
console.log("targetHere", target);
this.setState({
NumberHolder: target.value
});
};
But there is a bigger issue with your code. Since the value of your input will always be this.state.NumberHolder, you are simply setting the same value over and over again.
If you have a particular value you want to send on the click event, you can turn your click event into a curried function like this:
// pass in number as first argument to function that returns another anonymous function
clickHandler = (NumberHolder) => () =>{
this.setState({ NumberHolder });
};
And then on the element with the click event, pass the onClick like this:
<input onClick={this.clickHandler(3)} />
That will pass the argument in scope of the function, and allow you to access it.
Upvotes: 0