React / 2 MIN READ
Creating Cards
Component to Display Cards from JSON
From the original Fervor library. Examples may use older package versions.
Tutorial: Creating a Reusable Card Component in React Using JSON Data
Step 1: Install Dependencies
We’ll start off by creating a new React application and installing the necessary dependencies. Create a new React application by running the command:
npx create-react-app react-card-component
Then, navigate to your new project directory:
cd react-card-component
Next, install the react-markdown library:
npm install react-markdown
This package will help us to render markdown files as React components.
Step 2: Define the JSON Data
Create a new file named data.json in your src directory. This file will hold the data for our cards. Each object will have an id, an image path, and a markdown path.
[
{
"id": 1,
"image": "https://via.placeholder.com/150",
"markdown": "https://raw.githubusercontent.com/user/repo/branch/docs/md1.md"
},
{
"id": 2,
"image": "https://via.placeholder.com/150",
"markdown": "https://raw.githubusercontent.com/user/repo/branch/docs/md2.md"
}
]
In this case, I’ve used placeholder images and dummy URLs for the markdown files. Replace them with your actual URLs.
Step 3: Create the Card Component
Next, let’s create the reusable Card component.
import React, { useState, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
const Card = ({ data }) => {
const [markdownText, setMarkdownText] = useState('');
useEffect(() => {
fetch(data.markdown)
.then(response => response.text())
.then(text => setMarkdownText(text))
.catch(error => console.error(error));
}, [data]);
return (
<div className="card">
<img src={data.image} alt="" />
<ReactMarkdown>
{markdownText}
</ReactMarkdown>
</div>
);
};
export default Card;
This Card component fetches markdown file content from a provided URL, converts the fetched data to text, and sets the text to the markdownText state variable. The component then renders an image and the markdown text inside a div.
Step 4: Implement the Card Component
Finally, we will create an App component in the App.js file that imports and uses our Card component.
import React from 'react';
import Card from './Card';
import cardData from './data.json';
function App() {
return (
<div className="app">
{cardData.map((data) =>
<Card key={data.id} data={data} />
)}
</div>
);
}
export default App;
This App component imports the data from our data.json file and maps over it to create a Card for each object in the array.
And that’s it! We now have a reusable Card component in React that takes data from a JSON file and fetches and displays image and markdown content accordingly. Remember, you can style these components further according to your design requirements.