handleChange method setState syntax

handleChange method setState syntax
0

Tell us what’s happening:

Why can’t I write the handleChange method like this:

handleChange (event) {
this.setState(state =>
return{ input: event.target.value })
}

Your code so far


class ControlledInput extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: ''
  };
  this.handleChange = this.handleChange.bind(this)
}

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

render() {
  return (
    <div>
      <input value={this.state.input} onChange={this.handleChange} />
      <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/78.0.3904.108 Safari/537.36.

Challenge: Create a Controlled Input

Link to the challenge:
https://www.freecodecamp.org/learn/front-end-libraries/react/create-a-controlled-input

Welcome to the forum!

You have not asked a question, so we do not know what kind of help you need.

When using arrow function syntax, you can return a value implicitly like below:

const func = () => 'some value';

OR explicitly like below:

const func = () => {
  return 'some value'; 
};

Both of the above return the string “some value”.

Now, let’s say you want an arrow function to return an object literal like:

{ someProp: 'some prop value }

If you want to return the object explicitly, you would use:

const func = () => {
  return { someProp: 'some prop value };
};

It is slightly different when you want to return the object implicitly, which I assume is what you thought you were doing in the code above. When JavaScript encounters a { immediately after =>, this { represents the start of a code block (allows you to write multiple statements). It also means, you must use must use the return keyword to return a specific value. So how do you convince JavaScript you want to implicitly return an object? You must surround the object with ( and ).