Get Data From A JSON File in Gatsby Without GraphQL

I'd like to share a pretty common pattern I've been using for Gatsby projects if you want to have a JSON file where you can quickly add a new list item and have it propagate to the UI.
I usually use this technique as a reference without leaving the project before setting up the graphql and other data sources.
Yes, you don’t need GraphQL.
If you don’t know what Gatsby is, it is a static site generator built in React. You can use React to build the components of the website and give them to Gatsby, which will then generate a blazing fast website for you.
Let us build a site from scratch and then a create JSON file that contains some data.
Let’s Start
Run npm init gatsby
. Use the -y flag and pass the directory name you'd like to use for your project. This will create an initial Gatsby site in that directory. Navigate to it and open up your text editor.
Run yarn develop
in order to see the site available on localhost.
Adding Data
Create the directory and JSON file that has information on it. The path is just a personal preference.
In this example, mine will live inside src/data/bookmarks.json.
{
"content": [
{
"title": "Serverless Handbook for Frontend Engineers",
"link": "https://serverlesshandbook.dev/"
},
{
"title": "readme.so - Easiest Way to Create A README",
"link": "https://readme.so/"
},
{
"title": "The Fastest Frontend for the Modern Web",
"link": "https://www.gatsbyjs.com/"
}
]
}
Create a Component
Next, we create a component which will get the data from the JSON and render it to the webpage.
import React from "react";
import BookmarksData from "../data/bookmarks.json";
const Bookmarks = () => (
<>
<ul>
{BookmarksData.content.map((data, index) => {
return (
<li key={`content_item_${index}`}>
<a
href={`${data.link}`}
rel="noopener noreferrer"
target="_blank"
>
<h4>
{data.title}
</h4>
</a>
</li>
);
})}
</ul>
</>
);
export default Bookmarks;
Finally, now you can import this component in your index.js or app.js. The result will look like this:
Conclusion
In this post, I explained and made a small demo to show how we can get data from a JSON file in Gatsby without GraphQL. There may be some minor errors. If you find any, please let me know.
Thanks for reading through.