Gfullam has a posted a great answer.
I'll expand it a bit and provide some alternative solutions. Most of these are probably overkill for your particular case. However I believe you (and potential future readers) might find these useful. Note that these require ES6.
Template Literal Expression
Since you already have your code stored in a variable, you could use a Template Literal Expression. This is might be preferable if you have many variables or if you want to control your output.
class SomeComponent extends React.Component {
render() {
var foo = 1;
var bar = '"a b c"';
return (
<pre>{`
var foo = ${foo};
var bar = ${bar};
`}</pre>
)
}
}
ReactDOM.render(
<SomeComponent />,
document.getElementById('content')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="content"></div>
Perhaps not needed in this particular implementation, but it might be good to know that also can do function calls and other operations within the brackets.
CodePen
Tagged Template Literals
If you don't want to manually add line-breaks, semi-colons and other code formatting for your <pre>
tag, you could use a Tagged Template Literal to return the right output for you. Just provide it with the variables to output!
class SomeComponent extends React.Component {
pre(strings, variables) {
return variables.map((v, i) => {
return `var ${v.name} = ${v.value};
`
})
}
render() {
var variables = [{name: "foo", value: 1},{name: "bar", value: '"a b c"'}];
return <pre>{this.pre`${variables}`}</pre>;
}
}
ReactDOM.render(
<SomeComponent />,
document.getElementById('content')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="content"></div>
PS: Isn't this awesome!?
CodePen
const someCodeIWantToFormat = "var foo = 1"; const preBlock = (<pre> pythonCode </pre>); render(){ return (<div>{this.preBlock}</div>) };
im using es6