Max
Max

Reputation: 15975

Render JavaScript inside a <code> tag with JSX

I am using React to render some UI components. I would like to display some JavaScript code inside of <code> tag. I've tried the following:

class A extends React.Component {
    render() {
        return(
            <pre><code>
                (function(a, b) {
                    var s = a.prop;
                    // ...
                }(c, d));
            </code></pre>
        );
    }
}

When I try to compile this script with webpack and Babel, I get an unexpected token error at the line var s = a.prop. How can I properly render this JavaScript?

Upvotes: 1

Views: 5007

Answers (1)

azium
azium

Reputation: 20624

@Pamblam is right, you quite literally need a string:

  render() {
    var foo = `
      (function(a, b) {
        var s = a.prop;
        // ...
      }(c, d));
    `

    return (
      <pre>
        <code>{foo}</code>
      </pre>
    )
  }

fiddle

Upvotes: 4

Related Questions