user8463989
user8463989

Reputation: 2459

How to get input values using functional component with useState

When using a class based component I could get all of the field inputs by simply doing this:

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

Then in the actual form element I had:

onChange={this.handleChange}

I am now using a functional component and it doesn't seem that easy.

Having to add a different onChange handler to each form input is a pain eg:

const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
onChange={event => setFirstName(event.target.value)}
onChange={event => setLastName(event.target.value)}
onChange={event => setEmail(event.target.value)}

Is there a way to achieve the below using a functional component?

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

Upvotes: 2

Views: 2543

Answers (1)

Chad
Chad

Reputation: 618

Combine both firstName and lastName into one state and set each property based on the event.target.name. The spread operator preserves the current state and overwrites with the incoming update.

const [name, setName] = useState({
  first: '',
  last: ''
});    

handleChange = event => {
  setName({
    ...name, 
    [event.target.name]: event.target.value
  });
};

Upvotes: 4

Related Questions