A collection of useful code snippets that I've created or discovered that might help other developers. Feel free to copy and use them in your projects.
A simple responsive grid layout using Tailwind CSS that adjusts based on screen size
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
<div class="bg-gray-100 p-4 rounded shadow">Item 1</div>
<div class="bg-gray-100 p-4 rounded shadow">Item 2</div>
<div class="bg-gray-100 p-4 rounded shadow">Item 3</div>
<div class="bg-gray-100 p-4 rounded shadow">Item 4</div>
</div>
How to properly type React's useState hook with TypeScript
import React, { useState } from 'react';
interface User {
id: number;
name: string;
email: string;
}
const UserProfile: React.FC = () => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState<boolean>(true);
// Rest of component
return (
<div>
{loading ? (
<p>Loading...</p>
) : user ? (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
) : (
<p>No user found</p>
)}
</div>
);
};
A basic API route handler in Next.js with TypeScript
import type { NextApiRequest, NextApiResponse } from 'next';
type Data = {
name: string;
message: string;
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data | { error: string }>
) {
if (req.method === 'GET') {
res.status(200).json({
name: 'John Doe',
message: 'Hello from the API!'
});
} else {
res.status(405).json({ error: 'Method not allowed });
}
}
Different ways to center elements using CSS Flexbox
/* Center horizontally and vertically */
.center-both {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Optional, for full-height containers */
}
/* Center horizontally */
.center-horizontal {
display: flex;
justify-content: center;
}
/* Center vertically */
.center-vertical {
display: flex;
align-items: center;
height: 100%; /* Container needs height */
}
/* Space items evenly */
.space-evenly {
display: flex;
justify-content: space-between;
}
Designed and Developed by Ishimwe Richard
Build with Next.js & Chadcn. Hosted on Vercel.