Home > Enterprise >  Error: Objects are not valid as a React child. When i use a child property
Error: Objects are not valid as a React child. When i use a child property

Time:05-17

I am getting this error in my react app:

Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead.

In my react Component i called an API and getting a reasponse as a Json like this:

{    
title: "myTitle",
description: "My Description",
...
state: {
    id: 1,
    stateTitle: "active"
  },
}

I can use all the proberties, but not the property from the child object.

const myComponent = () => {

    ...useEffect...API call...



    return (
        <div>
             <h1>{data.title}</h1> <<--- This works fine... 
             <span>{data.state.stateTitle}</span> <<--- here i am getting the error
        </div>

    );
}

export default myComponent;

i tried to display the values with the JSON.stringify() methode, this works also fine.

<span>{JSON.stringify(data.state)}</span> // result: {"id":i,"stateTitle":"active"}

Or print with console.log(data.state.stateTitle); works as expected..

Why i am getting this error, when i try to print the value from a child element.

CodePudding user response:

I believe you have initialised data with a default value which is probably failing in the render part. The component renders the division with that default data before calling the API. Once the API response is received, the component will get re-rendered with the fetched response.

  • Related