9

I have Next JS project with static JSON placed in /pages/api/data.json that looks like this:

{
 "Card": [
   { "title": "Title 1", "content": "Content 1" },
   { "title": "Title 2", "content": "Content 2" },
   { "title": "Title 3", "content": "Content 3" }
 ]
}

I'm trying to get the content from that JSON to load in a couple of sections like this:

import { Card } from "../api/data";

export const getStaticProps = async () => {
  return {
    props: { cardData: Card },
  };
};

export default ({ cardData }) => (
  <>
    const card = cardData.title; console.log(cardData);
    { {cardData.map((cardData) => (
      <div>
        <h3>{cardData.title}</h3>
        <p>{cardData.content}</p>
      </div>
    ))}; }
  </>
);

But I'm getting a Type: Undefined error and I'm pretty sure that's not how the function should look like.

Also, if I want to export that as a component that I can use in my index.js, would I have to name the export default function? repo link here: https://github.com/DoctorSte/remoteOS

Jura Gorohovsky
  • 9,886
  • 40
  • 46
Steph
  • 443
  • 2
  • 4
  • 15

2 Answers2

15

No need for getStaticProps here, Webpack will bundle the JSON for you at build time. Here's a working example with your contact.js page:

import "tailwindcss/tailwind.css";

import Footer from "./components/footer";
import Form from "./components/form";
import Navbar from "./components/Navbar";

import Cards from "./api/data.json"

export default function Contact() {
 
 console.log(Cards['Cards 1'][0].title); // Title 1

 return (
    <>
      <Navbar />
      <Form />
      <Footer />
    </>
  );
}
OGreeni
  • 572
  • 5
  • 17
Alex A.
  • 845
  • 8
  • 10
1
  • In my case I imported it like the example below

mock/database.json

[
  {
    "id": 1,
    "name": {
      "first": "John",
      "last": "Smith"
    },
    "total": 2795.95,
    "status": "On Hold",
    "method": "PayPal",
    "date": "15 Minutes ago"
  },
  ...
]

components/RecentOrders.tsx

import data from "@/mock/database.json";

const RecentOrders = () => {
  return <div>{JSON.stringify(data, null, 2)}</div>;
};

export default RecentOrders;

serdarsen
  • 193
  • 2
  • 8