Stuck on React Challenge: React: Create a Controlled Input
the target property of the event argument in handleChange(event) is ‘undefined’, I have no idea why. Please help
My code so far
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
input: 'a'
};
// change code below this line
this.handleChange = this.handleChange.bind(this);
// change code above this line
}
// change code below this line
handleChange(event) {
this.setState(state => ({
input: event.target.value
}));
}
// change code above this line
render() {
return (
<div>
{ /* change code below this line */}
<input value={this.state.input} onChange = {this.handleChange} />
{ /* change code above this line */}
<h4>Controlled Input:</h4>
<p>{this.state.input}</p>
</div>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36.
Challenge: Create a Controlled Input
Link to the challenge:
Learn to code. Build projects. Earn certifications.Since 2015, 40,000 graduates have gotten jobs at tech companies including Google, Apple, Amazon, and Microsoft.
padunk
March 21, 2020, 4:58am
3
You don’t have to passed callback function inside setState. Just write the object you want to change inside setState will do.
this.setState({hello: 'hello world'})
benino
April 11, 2020, 5:57am
4
I was confused by this lesson as well. I had passed the same parameter to the setState function as shown above. The reason is that in this lesson:
https://www.freecodecamp.org/learn/front-end-libraries/react/use-state-to-toggle-an-element
it instructed us to set up the setState parameter that way.
I continued that pattern in this lesson:
https://www.freecodecamp.org/learn/front-end-libraries/react/write-a-simple-counter
here is my setState function which worked find in that lesson:
this.setState(state =>({count: 0}));
Can you explain why that works there but this doesn’t work in this lesson?
this.setState(state => ({input: event.target.value}));
this line does work:
this.setState({input: event.target.value});
on another note… even though the first function call doesn’t work it still passes when you click “Run the Tests” :-p
Thanks so much. It would be helpful to know.
padunk
April 15, 2020, 2:45am
5
You can read the docs for better explanation here:
Anytime we pretend to use an event to update state, is better to previously store it in a variable. Example:
let updateStateWithEvent = e.target.value
setState(s=>({value: s.value+updateStateWithEvent}))
or e.target.value dies before being useful
For this particular exercise:
handleChange(e){
let storeMe = e.target.value
this.setState(s=>({input:storeMe}))
}
Though here we’re not really updating anything and this should be enough
handleChange(e){
this.setState({input:e.target.value})
}