Sometimes, we want to pretty print JSON within React components.
In this article, we’ll look at how to pretty print JSON within React components.
Pretty Print JSON within React Components
To pretty print JSON within React components, we call call JSON.stringify
with extra arguments.
For instance, we write:
import React from "react";
const data = { a: 1, b: 2 };
export default function App() {
return (
<>
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
</>
);
}
to call JSON.stringify
with 2 as the 3rd argument.
This will make the returned JSON string have 2 spaces for indentation at each level.
Therefore, we should see:
{
"a": 1,
"b": 2
}
rendered.
Conclusion
To pretty print JSON within React components, we call call JSON.stringify
with extra arguments.