December 27, 2019
0 strokes bestowed

How to Render an Object in React

Building a `Log` Component

edit

The trick I'm about to show you I learned so early on in my days of learning React that it didn't dawn on me that others still don't know it. My apologies, let's fix that right now.

Have you ever made the mistake of trying to display an object in a React component?

const Component = ({ obj }) => <div>{obj}</div>

And been met with this?

Error message from attempting to render an object

Classic mistake. Don't worry, we've all made it a time or two. We can't render an object, but we can render strings. What if we turn the object into a string and render it then?

We can do that with JSON.stringify (docs). JSON.stringify takes an object and turns it into a JSON string. We can make a component that does this for us.

// I encourage you to look at the JSON.stringify docs to understand the
// `replacer` and `space` arguments
const Log = ({ value, replacer = null, space = 2 }) => (
  <pre>
    <code>{JSON.stringify(value, replacer, space)}</code>
  </pre>
)

We can now use this component anywhere we would like to display an object in our app. This is very useful for debugging apps.

{
  "name": "Kyle Shevlin",
  "age": 34,
  "location": "Portland, OR"
}

Use this whenever you'd like to display your object in the browser instead of looking at the object value in the console or the devtools.


Finished reading?

Here are a few options for what to do next.

Like
Liked the post? Click the beard up to 50 times to show it
Share
Sharing this post on Twitter & elsewhere is a great way to help me out
Support
Was this post valuable to you? Make a donation to show it
Make a Donation
Kofi logo

Newer Post: The Future of Second Career Devs
Tags
React

Let's talk some more about JavaScript, React, and software engineering.

I write a newsletter to share my thoughts and the projects I'm working on. I would love for you to join the conversation. You can unsubscribe at any time.

Data Structures and Algorithms Logo
Data Structures and Algorithms

Check out my courses!

Liked the post? You might like my video courses, too. Click the button to view this course or go to Courses for more information.
View on egghead.io
Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, React and front end web development.