Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSX to JSON or String and then back again

I want to save the state of a React Component in a database.

Json.stringify(myComponent);

However, when I try to use the component again with JSON.parse I get

Error: Objects are not valid as a React child (found: object with keys {type, key, ref, props, _owner, _store})

It is a JSON array. I read that this is caused by JSX keys.

Is there any package that allows me to save JSX as a string or object and then render it again as a React component?

like image 304
Wyatt Benno Avatar asked Jun 16 '17 06:06

Wyatt Benno


2 Answers

I was playing with something like this where i want to store a representation of a react component in database and render it back. After a bit of research i figured a way to store the component as JSON blob and render it back to UI.

Ckeck it out. https://gist.github.com/praveensastry/132eacff4a684a48e73cae21f2451078

like image 115
Praveen Sastry Avatar answered Sep 23 '22 01:09

Praveen Sastry


This is an old question, but since I stumbled upon it on my own search, it may be the case that someone else does.

If you want to store a JSX in a JSON without transforming it to static markup or a string or using other external libraries, you can achieve this with plain react/react api.

In my use case, I needed to both create new objects but also retrieve existing ones from storage/DB, so I was looping through an object, and one of the keys of said object was a component/JSX.

Example:

const experiment = <img src={sampleImagePath}></img>;
const example = { object: experiment }

Then, somewhere in the code, we have the function that is returning whatever JSX we have in the object. In my case, looped through an object and returned the elements that had been stored in the JSON.

return (
  <div>
    {React.createElement(object.type, object.props)}
  </div>);

The key part being React.createElement, which you can read more about in the docs in case you need to: https://reactjs.org/docs/react-api.html#createelement

It may not cover every use case, but it could be a good starting point. I know that having this as an answer would have saved me a couple of minutes of searching through SO and the react docs.

like image 39
PitBoss Avatar answered Sep 24 '22 01:09

PitBoss