Skip to content Skip to sidebar Skip to footer

How To Render A String With Jsx In React

I need to render an HTML (JSX) string in a React class. I don't know if this is possible or not. dangerouslySetInnerHTML is not valid for me because I have different react componen

Solution 1:

You can use babel to transform it

npm install --save babel-core

Then in your code

var babel = require('babel-core');
varComponent = eval(babel.transform('<div><MyComponent /></div>').code);

Please note that it is generally a bad idea to convert strings to executable code.

Solution 2:

The most upvoted answer simply does not work, skips various crucial steps, and doesn't explain where the code should go. I'm not sure if the poster just didn't actually run the code or what. Anyways, to actually get it working you need to do something like this:

npm install @babel/core

npm install @babel/preset-react

You need to use babel to transform the JSX into valid javascript that can run clientside on the server side. The serverside code in next.js

exportasyncfunctiongetServerSideProps() {
    const stringToRender = require('@babel/core').transform('<h1><Component/></h1>', {presets: ['@babel/preset-react']});
    return {
        props: {
            stringToRender
        }
    }
}

Now we need to evaluate the string on the client:

importReactfrom'react';
importComponentfrom'../component'; // Import your componentexportdefaultfunctionPage({stringToRender}) {
    const [content, setContent] = useState(null);
    
    useEffect(()=>{
        // It is necessary to evaluate within useEffect and window so that React are available.window.Component = Component; // This makes Component defined in the `eval` call.setContent(eval(stringToRender))
    }, [])
    
    return (
        <div>
            {content}
        </div>
    )
}

exportasyncfunctiongetServerSideProps() {
    const stringToRender = require('@babel/core').transform('<h1><Component/></h1>', {presets: ['@babel/preset-react']});
    return {
        props: {
            stringToRender
        }
    }
}

This code will actually run to the desired effect. If you have any additional components to render you will need to set them individually on the window object so that the components will be defined when the eval() call is made.

Post a Comment for "How To Render A String With Jsx In React"