skip to Main Content

I have a React state that has some objects in it.

StateObj = {
 a: "one",
 b: 2,
 option: {
  c: "value"
 }
}

Now I want to be able to clone this object option value c without referencing it like when React mounts, because this value will eventually be overwritten by an input onChange func, the reason why im doing this is because I want to able to reset the input if the user leaves the input empty.

<InputComp 
 value={StateObj.option.c}
 onChange={(e) => props.onChange(["option", "c"], e.target.value)}
>

2

Answers


  1. Follow up to my comment on the OP.

    Here is an example:

    import React, { useState, useEffect, useRef } from 'react';
    
    function YourComponent(props) {
      const [stateObj, setStateObj] = useState({
        a: "one",
        b: 2,
        option: {
          c: "value",
        },
      });
    
      const originalOption = useRef(null); // this will hold the original option object
    
      useEffect(() => {
        // On mount, store the initial value of the option object
        originalOption.current = JSON.parse(JSON.stringify(stateObj.option));
      }, []);
    
      const handleChange = (path, value) => {
        // your existing logic here to change the value
        if(value === '') {
          // if the input is emptied, reset the option object
          setStateObj(prevState => ({
            ...prevState,
            option: originalOption.current
          }));
        } else {
          // if there's a value, update the state normally
          // your logic here
        }
      };
    
      return (
        <InputComp
          value={stateObj.option.c}
          onChange={(e) => handleChange(["option", "c"], e.target.value)}
        />
      );
    }
    

    I highly suggest reviewing this post as well.

    What is the most efficient way to deep clone an object in JavaScript?

    Login or Signup to reply.
  2. To clone an object without referencing it, you can use the spread operator (...) or the Object.assign() method to create a shallow copy of the object. This way, any changes made to the cloned object won’t affect the original one. Here’s how you can achieve this in your React component:

    Using the spread operator:

    const clonedOption = { ...StateObj.option };
    
    // Pass the cloned option to the InputComp
    <InputComp 
      value={clonedOption.c}
      onChange={(e) => props.onChange(["option", "c"], e.target.value)}
    >
    

    Using Object.assign():

    const clonedOption = Object.assign({}, StateObj.option);
    
    // Pass the cloned option to the InputComp
    <InputComp 
      value={clonedOption.c}
      onChange={(e) => props.onChange(["option", "c"], e.target.value)}
    >
    

    Both of these methods will create a new object, clonedOption, which is a shallow copy of StateObj.option. Changes made to clonedOption won’t be reflected in the original object StateObj.option.

    This way, you can safely use the clonedOption as the value for your input field, and when the user leaves the input empty, you can reset the input to the original value if needed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search