tag in React and JSX
I am trying to use the pre tag inside of JSX.When you use the pre tag in JSX, it doesn\'t format at all. Why? In order to use the pre tag I need to do something like this:>
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.
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 (
{`
var foo = ${foo};
var bar = ${bar};
`}
)
}
}
ReactDOM.render(
,
document.getElementById('content')
)
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
If you don't want to manually add line-breaks, semi-colons and other code formatting for your 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 {this.pre`${variables}`};
}
}
ReactDOM.render(
,
document.getElementById('content')
)
PS: Isn't this awesome!?
CodePen