Within my React application, I store a javascript object in the localStorage. This object represents the theme used in the app. The problem is that one of the components of this object is a JSX
element:
{
icon: <Logo />,
}
I then use this object all over my app:
render() {
return (
<>
{theme.icon}
</>
)
}
The problem now is when I save this object in localStorage using JSON.stringify()
, the JSX object is ‘broken’ and is no longer considered a React object after using JSON.parse()
.
If I look to the localStorage, the icon
element is stored like this:
{key: null, ref: null, props: {width: "154", height: "79", viewBox: "0 0 154 79"}, _owner: null,…}
So have you an idea of I can store, extract and then use a JSX element from localStorage?
Advertisement
Answer
Why not change the icon value to string that reference which type of icon you want.
Example:
the object stored in localStorage :
{
icon: "logo",
}
and in your code just make a condition :
render() {
return (
<>
{theme.icon === 'logo'? <Logo /> : null}
</>
)
}
or make an Icon generic component that takes the type of icon as a prop and render the correct one :
render() {
return (
<Icon type={theme.icon}/>
);
}