mrpbennett
mrpbennett

Reputation: 1956

Object are not valid as a React child in React

I have read a few anwsers on SO but none seem to come across what I need.

I have a function:

const geoDataRTB = () => {
  return data.map((result) => result.request.buyerContext.request.geoData);
};

Which returns a json object.

"geoData": {
                        "type": "GPS",
                        "areaCode": "586",
                        "city": "MACOMB",
                        "country": "USA",
                        "metro": "505",
                        "latitude": "42.311859",
                        "longitude": "-85.579595",
                        "state": "MI",
                        "postalCode": "48042",
                        "bandwidth": "MOBILE",
                        "sic": "517312",
                        "domain": "MYVZW.COM",
                        "cityCode": 0
                    },

For example...currently I am returning geoData.city but id rather return the whole geoDta object instead. The end result is displayed via this

<section id='returnedData' className='mt-5 pb-5'>
        <h2 className={h2Styles}>result</h2>
        <div className='bg-gray-700 text-white rounded-md p-5 mt-5 '>
          {data.map((result, i) => (
            <div className='py-1'>
              <span className='text-xs text-gray-400 font-mono'>Capture {i} : </span>
              <span className='font-mono'>{result}</span>
              <br />
            </div>
          ))}
        </div>
      </section>

But when trying to return the geoData i get the object child error. Any suggestions on how to display the object? I have tried

const geoDataRTB = () => {
  return data.map((result) => result.request.buyerContext.request.geoData.toString());
};

But this just returns [Object, Object]

Upvotes: 1

Views: 48

Answers (2)

alexfertel
alexfertel

Reputation: 936

If you want to display JSON as-is, usually you write something like:

<pre>
     {JSON.stringify(OBJECT, null, 2)}
</pre>

That will show a javascript object pretty printed.

Upvotes: 1

Sunyatasattva
Sunyatasattva

Reputation: 5830

It looks to me like you want to display your data inside your monospace section, and not that you want to pass the data around for further manipulation or styling it in a different way.

If that's the case, you'll need to do:

const geoDataRTB = () => {
  return data.map(result => JSON.stringify(result.request.buyerContext.request.geoData));
};

Upvotes: 1

Related Questions