Reputation: 329
I need to display a fixed javascript code without running on my website. I only need to display it and not have it run. I am using react as the application. I researched online and I saw the way to do it is using the pre tag. But when I include the code within the pre tag, I think the open close curly brackets are causing an error. I am not sure how else to display a fixed code snippet using react. There are a lot of open close brackets in the code and I will not be able to use `` everywhere. Is there any other way to implement this? I have included my code below to show what I mean.
<pre className={styles.rawExampleSectionCode}>
{
"objectType": "list",
"uri": "",
"data": [
{
"id": "57dafe43317467e7b0ef5276",
"projectId": "54c17e92e4b0bc49e27d9398",
"number": 5,
"startingUserId": "57a28b28961401f240812caf",
"queued": 1473969731915,
"started": 1473969754283,
"completed": 1473969762970,
"status": "Succeeded",
"commitId": "1c6e8aa47951e39f9a905f0077af9355c35b712b",
"executor": "us-west-2:i-007942020ce7baeb5",
"outputCommitId": "73fe9481fe635bada713246c3c739beefa424e8c",
"title": "Run with great R^2 of 1!",
"isArchived": false,
"postProcessedTimestamp": 1473969767822,
"diagnosticStatistics": {
"isError": false,
"data": [
{
"key": "R^2",
"value": "1.000"
}
]
},
"isCompleted": true,
"hardwareTierId": "gpu"
}
]
}
</pre>
Upvotes: 9
Views: 9094
Reputation: 4421
You almost had it, just make the object a template literal and then inject it into a <code>
element within your JSX. Now it will display as expected in the React component.
const obj = `{
"objectType": "list",
"uri": "",
"data": [
{
"id": "57dafe43317467e7b0ef5276",
"projectId": "54c17e92e4b0bc49e27d9398",
"number": 5,
"startingUserId": "57a28b28961401f240812caf",
"queued": 1473969731915,
"started": 1473969754283,
"completed": 1473969762970,
"status": "Succeeded",
"commitId": "1c6e8aa47951e39f9a905f0077af9355c35b712b",
"executor": "us-west-2:i-007942020ce7baeb5",
"outputCommitId": "73fe9481fe635bada713246c3c739beefa424e8c",
"title": "Run with great R^2 of 1!",
"isArchived": false,
"postProcessedTimestamp": 1473969767822,
"diagnosticStatistics": {
"isError": false,
"data": [
{
"key": "R^2",
"value": "1.000"
}
]
},
"isCompleted": true,
"hardwareTierId": "gpu"
}
]
}`;
const Snippet = () => {
return (
<pre>
<code>{obj}</code>
</pre>
)
};
ReactDOM.render(<Snippet />, document.getElementById("root"));
pre {
background: #eee;
padding: 1rem;
overflow: auto;
border-radius: 3px;
max-width: 80ch;
}
pre code {
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
}
<body>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
</body>
Upvotes: 9