Home > Enterprise >  Rendering json data in react js error: 'TypeError: Cannot read properties of undefined (reading
Rendering json data in react js error: 'TypeError: Cannot read properties of undefined (reading

Time:05-01

So I am trying to render some data from a json file in react js, but when I try to run it, it always show an error that it cannot read the parent of a certain data from the json because it's undefined even though I am sure that I put it right.

Json file:

{
    "item": [
        {
            "name": "item"
        }
    ]
}

Code:

const main = ({ backEndData }) => {
  return (
    <div className='main'>
        {
            backEndData.items.item.forEach(product => {
                return (
                    <p>{product.name}</p>
                )
            })
        }
    </div>
  )
}

Error:

enter image description here

I am getting the json file from my backend server btw

CodePudding user response:

I advise you to read about the difference between map and foreach (forEach never return smth). Try displaying items in the console (they are not defined). I can assume that your code will look like this:

backEndData.item.map(product => 
  <p>{product.name}</p>
);

CodePudding user response:

If backEndData is the object you're showing, it's obvious it does not have a items property. So backEndData.items is undefined. You can't access any property on undefined (you'll just get the error you're getting).

You probably mean

  <div className='main'>
    {backEndData.item.map(product => (<p>{product.name}</p>))}
  </div>

For the sake of good naming conventions, I think the best thing to do is rename item in your json to items, while changing the above to

  <div className='main'>
    {backEndData.items.map(product => (<p>{product.name}</p>))}
  </div>

, accordingly.

Another note: if backEndData is fetched from the server and it's not available initially, you either condition the component rendering based on its value, in parent component (e.g:

<div>
  {data && (<Main backEndData="data" />)}
</div>

) or, alternatively, you use optional chaining (?.) inside <Main>:

<div className='main'>
  {backEndData.items?.map(product => (<p>{product.name}</p>))}
</div>
  • Related