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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With