skip to Main Content

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


  1. You are close! days is an array of object but you are not treating it that way in the code. Change your Diary component to something like this so that it loops through days and displays an h2 for each day in the array:

    import React from 'react';
    
    const Diary = ({ data }) => (
      <div>
        {data.map(day => {
            return (
                <h2>
                    {day.daytitle}
                </h2>  
            )
        })
      </div>
      
    );
    
    export default Diary;
    
    Login or Signup to reply.
  2. 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 a days property.

    If you want a component which takes in an array and then iterates through it, you have to use .map:

    const Diary = ({ days }) => (
      <>
        {days.map(({ daytitle }, key) => (
          <div key={key}>
            <h2>{daytitle}</h2>
          </div>
        ))}
      </>
    )
    

    Or you could have a DiaryEntry responsible for rendering a single day and handle the looping/mapping outside:

    const DiaryEntry = ({ day }) => (
      <div>
        <h2>{day.daytitle}</h2>
      </div>
    )
    

    and use it as:

    import DiaryEntry from '../../components/DiaryEntry'
    
    const Diary = ({ days }) => (
      <>
        {days.map((day, key) => (
          <DiaryEntry {...{ day, key }} />
        ))}
      </>
    )
    

    Note: when mapping, you need a key. It doesn’t have to be the element’s index in the array. React uses this to identify the element in the array. It has to be a unique identifier (uuid, the actual date, …).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search