Mon Apr 17 2023
How to create a custom card component in React
In this guide, we will show how to implement a card component, very similar to our article cards we are using on this website.
Final result
Below image will show how the final result will look like.
Prerequisites
- A react application. Need to set one up? How to guides - using create-react-app or from scratch.
Implementation
So let's create our component. We will call it Card.tsx (or .jsx) and specify some props to provide it with.
import style from "./Card.module.scss"; interface ICardProps { title: string; href: string; text: string; imgSrc: string; created: Date; } export const Card = (props: ICardProps) => { const { title, href, text, imgSrc, created } = props; return ( <a href={href} className={style.card}> <img className={style.img} alt="card" src={imgSrc} /> <h2 className={style.title}>{title}</h2> <span className={style.text}>{text}</span> <div className={style.dateContainer}> <span className={style.created}>{created.toDateString()}</span> </div> </a> ); };
And now, let's give it some styling.
.card { display: flex; flex-direction: column; width: 250px; min-height: 350px; border-radius: 10px; box-shadow: 0rem 0.25rem 1rem RGB(0 0 0 / 10%); padding: 0.5rem 1rem; cursor: pointer; text-decoration: none; color: inherit; @media only screen and (max-width: 500px) { max-width: none; width: 90%; } .img { align-self: center; width: 80%; max-width: 240px; height: 130px; border-radius: 4px; margin-top: 0.5rem; object-fit: contain; } .title { margin-top: 1rem; } .text { margin-top: 1rem; font-size: 13px; } .dateContainer { display: flex; flex: 1; align-items: end; justify-content: end; .created { font-size: 11px; font-style: italic; margin-top: 0.5rem; } } }
And now you can consume it like this:
<Card title="My first card" text="My cool text that I want to share with my viewers" created={new Date()} href="/to-my-article" imgSrc="/my-image.png" />
Outro
In this short tutorial, we shared how we created our cards that we use to show our articles across our website. I hope you found this helpful, and that it might give you some inspiration on how you can create your own cards for displaying your own blog posts, articles or similar on your homepage.
Thanks for reading, and have a great day!
Mon Apr 17 2023
See all our articles