I have an mdx file with some data to create a blog post.
The mdx file structure is the following
---
title: MDX is Magical2!
path: /mdx2
date: 2019-08-25
---
import Diary from "../../components/Diary";
export const days = [
{
daytitle: "Day1",
description: "desc 1",
cover: "./img.jpg"
},
{
daytitle: "Day2",
description: "desc 2",
cover: "./img.jpg"
},
];
<Diary data={days} />
and my component Diary is the following:
import React from 'react';
const Diary = ({ data }) => (
<div >
<h2
>
{data.days.daytitle}
</h2>
</div>
);
export default Diary;
That give me the error: Cannot read properties of undefined (reading ‘days’)
Can someone help me to fix this?
Thanks
Another version I tried is
import React from 'react';
const Diary = ({ daytitle }) => (
<div >
<h2
>
{daytitle}
</h2>
</div>
);
export default Diary;
This doesn’t display nothing
2
Answers
You are close!
days
is an array of object but you are not treating it that way in the code. Change yourDiary
component to something like this so that it loops throughdays
and displays anh2
for each day in the array:The data you’re passing is an array (of days).
And you’re trying to read the
days
property of that array. Arrays don’t have adays
property.If you want a component which takes in an array and then iterates through it, you have to use
.map
:Or you could have a DiaryEntry responsible for rendering a single day and handle the looping/mapping outside:
and use it as:
Note: when mapping, you need a
key
. It doesn’t have to be the element’sindex
in the array. React uses this to identify the element in the array. It has to be a unique identifier (uuid
, the actual date, …).