0

I am looking for smart method to handle input change in React

I have input

<input type="text" name="name" onChange={(e) => this.handleInputChange(e)} />

And function to handle input change

handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
        [name]: value
    });
}

But I need to change sometimes not property of state, but property of state object (or property of property of state object...) for example:

const entity = this.state.entity;
entity[name] = value;
this.setState({
   entity: entity
)}

Some ideas for multilevel?

2
  • for multi-level, you can use dot notation, name="location.lat" for example, and write some code to iterate through the levels of the .notation or use a library Commented Dec 11, 2020 at 9:27
  • a library like this would do it: npmjs.com/package/object-path Commented Dec 11, 2020 at 9:28

1 Answer 1

1

Further to my comment, you might do something like this:

handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;
    
    this.setState(prevState => {
        const newState = Object.assign({}, prevState  );
        // https://www.npmjs.com/package/object-path
        ObjectPath.set(state, name, value);
        return state;
    });
}

using this library.

That way, when your input name is "a.b.c", it will go to the nested object state.a.b and change the c property

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.