Attempting to render an object in a React component results in an error. Objects are not valid React elements, however, strings are. If we transform an object using JSON.stringify()
into a string, we can render it just as we would any other string.
We can encapsulate this concern in a React component. We can then use this component in a React app wherever we might like to display an object on the screen. This is very useful for debugging purposes when console.log
or a debugger
are not your best options.
A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.
Instructor: I have a very simple React app here. I have one value, which is an object of my name, my age, my location that I'd like to display in the UI somehow. If I make the mistake, as many of us have, of accidentally trying to render this value and I save it, we're going to see that I get an error, "Objects are not valid as React child."
We need to turn this object into something valid so that React will render it. One way we can do that is with JSON.stringify. It turns it into a string and shows it on the page. We can make this a bit nicer by adding the replacer and space arguments.
If we change this from being a div to pre-encode elements instead -- let me do some rearranging here real quick -- we'll get it nicely formatted into our app.
We can also take this and make it a component. I'm going to call it log. Log will take a value prop, a replacer prop, which we will default to null, and a space prop, we will default to 2, and it will return this bit of code here.
I want to cut that out, paste it in here, replace null with replacer, and 2 with space, and then here I will call log with value set to value.
We have the same display, but now I have a component I can reuse in my application for whenever I would like to display an object onto the screen.
This is useful for debugging when it's easier to view the object in your browser rather than the console or even your developer tools. We can even give it a bit of a style so that it stands out a bit more in our application.