marcelomo
marcelomo

Reputation: 181

TypeError: Cannot read property when passing in a prop

I am getting an issue

TypeError: Cannot read property 'year' of undefined in my Timeline.js file

when I pass in a prop to a react component and want to get a specific variable from my prop. To explain, timelineyears.js is the array of data that has a year variable that I want to pass into TimelineItem.js . Finally, Timeline.js will loop through all of the TimelineItem to show the years, but I am getting a TypeError: Cannot read property 'year' of undefined when I compile. Any help would be much appreciated!

This is my timelineYears.js file

const timelineYears = [{
        year: 1925

    },{
        year: 1926
    },
    {
        year: 1927
    }

];

export default timelineYears;

This is my timelineItem.js file

import React from 'react';
import './timelineYears.js';


const TimelineItem = ({timelineYears}) => (
    <div className="timeline-item">
        <div className="timeline-item-content">
           {timelineYears.year}
        </div>   

    </div>

);

export default TimelineItem;

And finally, this is my Timeline.js file

import React from 'react';
import timelineYears from  './timelineYears.js';
import TimelineItem from './TimelineItem.js';


const Timeline = () => timelineYears.length > 0 && (
    <div className="timeline-container">
        {timelineYears.map((data, idx) => (
            <TimelineItem data = {data} key={idx} />
        ))}
    </div>
);

export default Timeline;

Upvotes: 0

Views: 40

Answers (2)

jjimenez
jjimenez

Reputation: 893

I think the problem is in your TimelineItem component. According to your code, you're expecting a property called timelineYears, however, you're passing a property called data.

This should work:

import React from 'react';
import './timelineYears.js';


const TimelineItem = ({data}) => (
    <div className="timeline-item">
        <div className="timeline-item-content">
           {data.year}
        </div>   
    </div>
);

export default TimelineItem;

Upvotes: 1

devnull69
devnull69

Reputation: 16544

Your property is called data in Timeline.js. so when you deconstruct in TimelineItem, it should also be called data rather than timelineYears

So get rid of everything called timelineYears in TimelineItem and replace it with data

import React from 'react';


const TimelineItem = ({data}) => (
    <div className="timeline-item">
        <div className="timeline-item-content">
           {data.year}
        </div>   

    </div>

);

export default TimelineItem;

Upvotes: 1

Related Questions