Search code examples
reactjsobjectjsxstringify

Converting a JSX object to string


I have an object in .jsx file that contains JSX.elements here and there. I want to convert it to string, e.g go from this:

const data = {
  title: 'Create cat',
  description: 'Creates a new cat',
  react_element: (
    <>
      <span>Create account body here</span>
      <VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" />
    </>
  ),
  generatePrettyReactElement: (args: string) => (
    <>
      <span>Create account body here</span>
      <VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" />
    </>
  ),
};

To this:

const string = "const data = { title: 'Create cat', description: 'Creates a new cat', react_element: (<> <span>Create account body here</span> <VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" /> </>),generatePrettyReactElement: (args: string) => (<> <span>Create account body here</span><VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" /></>),};"

I've tried JSON.stringify(data) but then it loses JSX.elements, then I've tried https://www.npmjs.com/package/react-element-to-jsx-string but it only works with JSX.Element and not an object that might contain JSX elements.


Solution

  • You can write replacer for JSON.stringify function and use react-element-to-jsx-string for each JSX element.

    JSON.stringify(data, (value) => {
      if (React.isValidElement(value)) {
         const result = /// do react element stringification of the element
         return result;
      }
    
      return value;
    })