javascriptjsxmithril.js

JSX Curly Braces Inside Script Tag?


This is a silly question but it's stumped me for a while now. I'm currently trying to design a Mithril.js component that returns a <div> object that includes a <script> tag. I've just trying to perform a couple tests and so far, my view() method, looks something like the following:

view() {
    return (<div>
        <script>
            var x = 5;
            alert(x);
            var y = {"a" : 1, "b": 3}; // Compiler complains about the curly braces in this line
        </script>
    </div>);
}

and everything seems find until the line where I try to define an object, where the compiler complains about the curly braces in that line. My VS Code editor asked if I meant to replace the braces with {'{'} and {'}'} or &lbrace; and &rbrace;, but that doesn't seem to solve the problem either. Is there some sort of way to include curly braces inside the <script> tag inside JSX?


Solution

  • You need to use dangerouslySetInnerHTML, however it is not recommended.

    <script
      dangerouslySetInnerHTML={{
        __html: `
                var x = 5;
                alert(x);
                var y = {"a" : 1, "b": 3};
            `,
      }}
    />