Home > Software design >  Can I convert a reference to a React Component into JSON?
Can I convert a reference to a React Component into JSON?

Time:03-27

I want to JSONify the state of a React component and dump the state into a database. My code currently looks like this:

const [exampleState, setExampleState] = useState([
   {
      componentName: "Test component",
      component: <TestComponent props={testComponentData} />,
   }.
   {
      componentName: "Another test component",
      component: <AnotherTestComponent props={anotherTestComponentData} />
   }
]);

Would it be possible to JSONify the state as is, store it in a database, retrieve the data from the database at a later date as a JSON, then convert it back into a valid state?

If not, what is the recommended procedure to convert this state into a JSON object that I could store in a database and convert it back from a JSON object into state again?

CodePudding user response:

I don't think the whole component can be store to DB like this way. The more reasonable way should be store the component name and props to DB and make the react component to stay in the frontend.

A brief example maybe like this.

DB

[
    {
      name: 'TestComponent',
      props: testComponentData
    },
    {
      name: 'AnotherTestComponent',
      props: anotherTestComponentData
    }
]

Frontend

import TestComponent from './TestComponent';
import AnotherTestComponent from './AnotherTestComponent';

const renderComponent = (name, props) => {
  const mapNameToComponent = {
    TestComponent: TestComponent,
    AnotherTestComponent: AnotherTestComponent
  }

  const Component = mapNameToComponent[name];
  
  if (!Component) return null;
  return <Component {...props} />
}

const Page = () => {
  const [name, setName] = useState();
  const [props, setProps] = useState();

  useEffect(() => {
    // call api to getDB data
    // The data structure of dbData just like the DB shows
    const dbData = getDB();

    // store the DB data in the state
    const TestComponentData = dbData[0];
    setName(TestComponentData.name);
    setProps(TestComponentData.props);
  }, [])
  
  // choice which component you want to render by name and props
  return renderComponent(name, props)
}
  • Related