Create a Controlled Input passing setState a function

Tell us what’s happening:
Describe your issue in detail here.
Why does passing a function to the setState not work here? From the Use State to Toggle an Element lesson, I thought I could pass setState a function anywhere I need the most current values of the state and props. I am also confused by the difference between using value={this.state.input} vs passing the setState function I did below to update the state?

Thank you!

Whey
Your code so far


class ControlledInput extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: ''
  };
  // 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 type="text" 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/98.0.4758.102 Safari/537.36

Challenge: Create a Controlled Input

Link to the challenge:

I also am confused about why passing the function doesn’t work- does it have to do with how event.target.value works, or is it just because event.target.value isn’t set in the initial state?

This is really interesting, I think this may have to do with how react works. If you put the

state => ({input: event.target.value})

on a function like this

function updateInput (){
state => ({input: event.target.value})
}

and the call it in the setState, it seems to work. Maybe it also has to do that React setState is asynchronous. I will like to know more about this as well…

This thread has an explanation.

1 Like

Why aren’t we using the current state?

Because the previous state (or props) isn’t used to derive the new state. The new state is just whatever event.target.value is.

An example of a derived state update often given is a counter component where we take the previous state (and/or props) and add to it. Although simple counters usually work just fine without deriving the state.

1 Like