7

I'm new to React, and I'm trying to render a static CSS code sample within a React component, like this:

React.createClass({
  render: function() {
    return (
      <code> body { color: blue; } </code>
    )
  }
});

However, this does not seem to work.

Is there some special way for me to escape code like this, or am I doing something wrong?

4
  • 1
    Try <code>{"body { color: blue; }"}</code> Commented Apr 5, 2015 at 17:50
  • @ColonelThirtyTwo This does the trick, but I lose syntax highlighting for the portion in quotes. I don't suppose you are aware of an alternative in which syntax highlighting is preserved? Commented Apr 5, 2015 at 18:05
  • 1
    @AustinYork - As the suggestion is to put the content in a string literal, I'd be very surprised if any editor intentionally continued to syntax highlight the contents (as many devs wouldn't want that normally). Commented Apr 5, 2015 at 18:10
  • 1
    In WebStorm you can Alt-Enter -> Inject Language and choose the language for the string if you like. But it's not something most editors support. It's not code, it's a text string that happens to include code. Commented Apr 5, 2015 at 19:15

3 Answers 3

9

It is probably also worth noting that this can be done with multiline strings too:

<code>{`
  html { background: red; }
  body { color: blue; }
`}</code>
Sign up to request clarification or add additional context in comments.

2 Comments

Thats nice, because it's easy to pass parameters if needed, using ${myparam}
This works. Thanks for that! I needed to wrap this with <pre> tag to preserve the next line and original formatting.
7

@ColonelThirtyTwo's answer does the trick:

<code>{"body { color: blue; }"}</code>

Comments

0

If you want to do multiline you have to add line breaks as follows. If you don't they will all be on the same line.

    <code>
      {`html { background: red; }`}<br/>
      {`body { color: blue; }`}<br/>
    </code>

Comments

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.