Convert a string to a react component

Viewed 347

I have a string that's a react component coming back from an API request. Unfortunately, I have no control over how the data gets returned, so it comes back like

`<Sphere><meshBasicMaterial attach='material' color='pink' /></Sphere>`

All I want to do is be able to render the above in a react component, but because it's a string I can't. Ideally, without using any external libraries to convert it.

Am I missing something simple here? Any information helps!

// string = "<Sphere><meshBasicMaterial attach='material' color='pink' /></Sphere>"

function Scene({string}) {

  // const MyComponent = string

  const MyComponent = () => { return (string) }

  return (
    <>
      <Canvas>
        <MyComponent />
      </Canvas>
    </>
  )
}

Note - I stumbled upon this StackOverflow question, but is not a solution in my case due to extensive non-HTML tags.

3 Answers

Browsers don't understand jsx, so you'll need to compile it somehow. Normally that is done on the server, but if you need to do it on the client then you can use the Babel standalone js bundle: https://reactjs.org/docs/add-react-to-a-website.html#quickly-try-jsx

Note: since your string contains non-HTML tags, using dangerouslySetInnerHTML is not a solution in your case. Also note that you may still need to import the components mentioned in the string (in the example, the Sphere component).

Please follow the below example, basically, you need to evaluate string to element, we can use dangerouslySetInnerHTML.

const htmlStringElem = '<h1>Hello World!</h1>';

const App = () => (
  <div dangerouslySetInnerHTML={{ __html: htmlStringElem }} />
);

ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Since you are working with React, you can use Parse.

import parse from "html-react-parser";


const App = () => (
   {parse(<Sphere><meshBasicMaterial attach='material' color='pink' /></Sphere>)}

);

ReactDOM.render(<App />, document.body);

This is an easy and safe way to achieve this.

Related