1

I have a data object that I need to be able to iterate over which is an array of objects. I'm attempting to do so with Object.keys, but missing something with my implementation, as I get the error TypeError: Cannot read property 'metrics' of undefined.

The data object is constructed as such:

export const data = {
  metrics:
  [
    {
      number:'10',
      subText: 'content',
      tertiary: 'more content'
    },
    {...}
  ]
}

where the component is trying to iterate over the object like so:

 export const Metrics = (props) => {
  return (
      <div className="metric-container" aria-labelledby="metrics">
        {Object.keys(props.data.metrics).map((metric, i) => (
          <div className="metric"><h1>{metric.number}</h1><p>{metric.subText}</p><p>{metric.tertiary}</p></div>
        ))}
      </div>
    )
};

the data is imported into App.js with

import { data } from './assets/dataprops';

that has the component <Metrics {...data}/>

2 Answers 2

1

It should be:

<Metrics data={...data}/>

Otherwise, if you want to pass

<Metrics {...data}/>

You can access metrics like

 export const Metrics = (props) => {
  return (
      <div className="metric-container" aria-labelledby="metrics">
        {Object.keys(props.metrics).map((metric, i) => (
          <div className="metric"><h1>{metric.number}</h1><p>{metric.subText}</p><p>{metric.tertiary}</p></div>
        ))}
  </div>
)

};

Sign up to request clarification or add additional context in comments.

2 Comments

I went with the second option, and removed data from props.data.metrics so that its just props.metrics, but now none of the data is showing in the DOM.
@Matt It could be, because you don't a key in your <div className="metric"> ?
0
<Metrics {...data}/>

This passes each of the keys in data as props to Metrics. You can make one of two changes:

  1. Access props.metrics instead of props.data.metrics.

  2. Pass data as a prop:

    <Metrics data={data}>
    

I suggest that you install the React Developer plugin for your browser. This adds a "React" tab to the developer tools window. On this tab, you can inspect components and their props and state. Using this tool helps you track down problems like the one you encountered here. You would immediately see that the Metrics component has no prop named data but that it does have a prop named metrics.

Note that since metrics is an array, you do not need to call Object.keys(). You can simply do props.metrics.map() directly.

1 Comment

Using props.metrics.map() directly was the solution. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.