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
Follow up to my comment on the OP.
Here is an example:
I highly suggest reviewing this post as well.
What is the most efficient way to deep clone an object in JavaScript?
To clone an object without referencing it, you can use the spread operator (
...
) or theObject.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:
Using Object.assign():
Both of these methods will create a new object,
clonedOption
, which is a shallow copy ofStateObj.option
. Changes made toclonedOption
won’t be reflected in the original objectStateObj.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.