1

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?

2
  • 2
    you want to return a string, yet nothing is in quotes... Commented May 13, 2016 at 15:37
  • 1
    The above code is written in JSX syntax. What is being returned is a React element. The code to generate the React element is automatically generated by the JSX transpiler. Commented May 13, 2016 at 15:39

1 Answer 1

4

@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

Sign up to request clarification or add additional context in comments.

2 Comments

You can use {` ... `} to escape a multi-line string inside JSX.
@Aaron that's what I tried first and it didn't work. I just went back and tried again and it did. hmm. I thought the IIFE in the string was some edge case for brackets strings in jsx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.