0

I've got a handleChange event that pushes data into the props

handleChange = input => e => {
    let target = e.target,
        type = target.type,
        value = target.value;

    this.setState({ 
        [input]: (type === "checkbox" ? target.checked : value) 
    });
};

in the input, I handle the change onChange={onChange('services.cleaning')} Is there anyway i can push the data in the props as a nested object instead of as "services.cleaning"?

The onchange event

<Checkbox onChange={onChange('services.cleaning')} type='checkbox' name='cleaning' />
7
  • what's the structure of your object? Commented May 8, 2019 at 10:34
  • where are you calling onChange? paste the snippet Commented May 8, 2019 at 10:34
  • I've updated the post Commented May 8, 2019 at 10:36
  • where's your onChange function? Commented May 8, 2019 at 10:37
  • 1
    Will the depth of the nested prop always be equal to 2 ? can you have something like this 'prop1.prop2.prop3' ? Commented May 8, 2019 at 10:53

1 Answer 1

1

Here is one possible solution:

  • First, you need to create a new object (shallow copy) of this.state.services
  • Then you update the prop cleaning of this nested object
  • Lastly you update the state with this.setState({services: nestedObjectCreated})

Here is the corresponding code :

handleChange = propKey => e => {
   const {target} = e;
   const {type, value} = target;
   const newValue = type === "checkbox" ? target.checked : value

   const [firstProp, ...otherProps] = propKey.split('.');

   if (!otherProps.length) {
      return this.setState({[firstProp] newValue});
   }

   const nestedObject = {...this.state[firstProp]};
   otherProps.reduce(
       (acc, val, index) => {
          if (index < otherProps.length - 1) {
             return acc[val];
          }
          acc[val] = newValue;,
       },
       nestedObject
   );

   this.setState({[firstProp]: nestedObject});
};
Sign up to request clarification or add additional context in comments.

1 Comment

wow this is exactly what I needed, and thanks for explaining the solution, much love

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.