Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
FAQ Section Markup
A simple FAQ section using semantic HTML and details/summary elements.
<section class="faq-section" aria-labelledby="faq-title">
<h2 id="faq-title">Frequently asked questions</h2>
<details>
<summary>Can I use CodShot for free?</summary>
<p>Yes. The free plan is a good way to try the platform.</p>
</details>
Cross-Tab State Sync with BroadcastChannel
Synchronize lightweight UI state between tabs from the same origin.
const channel = new BroadcastChannel('app-preferences');
const preferences = {
theme: 'dark',
compactMode: true,
};
channel.addEventListener('message', (event) => {
if (event.data?.type !== 'preferences-updated') {
return;
}
Async Generator for Paginated API Data
Iterate through paginated API responses without loading every page into memory.
type Page<T> = {
items: T[];
nextCursor: string | null;
};
export async function* paginate<T>(
buildUrl: (cursor: string | null) => string,
): AsyncGenerator<T, void, void> {
let cursor: string | null = null;
do {
Next.js Loading Skeleton
Provide instant loading UI for an App Router segment with loading.tsx.
// app/dashboard/loading.tsx
export default function DashboardLoading() {
return (
<main aria-busy="true" aria-label="Loading dashboard">
<div className="skeleton skeleton-title" />
<div className="skeleton-grid">
Next.js Server Action Form with useActionState
Connect a Next.js Server Action to a client form with validation and pending state.
// app/actions.ts
'use server';
export type CreateUserState = {
message: string;
errors: {
email?: string;
};
};
export async function createUser(
previousState: CreateUserState,
formData: FormData,
): Promise<CreateUserState> {
React Error Boundary Component
Catch rendering errors in a subtree and provide a retryable fallback UI.
import {
Component,
type ErrorInfo,
type ReactNode,
} from 'react';
type Props = {
children: ReactNode;
fallback?: ReactNode;
};
type State = {
hasError: boolean;
};
export class ErrorBoundary extends Component<Props, State> {
state: State = {
Dynamic Page with notFound
Render the nearest not-found UI when a requested App Router record does not exist.
// app/products/[id]/page.tsx
import { notFound } from 'next/navigation';
type PageProps = {
params: Promise<{
id: string;
}>;
};
export default async function ProductPage({
params,
}: PageProps) {
const { id } = await params;
Non-Blocking Tabs with useTransition
Switch expensive tab content without blocking urgent UI updates.
'use client';
import { useState, useTransition } from 'react';
const tabs = ['overview', 'activity', 'settings'] as const;
type Tab = (typeof tabs)[number];
export function DashboardTabs() {
const [activeTab, setActiveTab] = useState<Tab>('overview');
Optimistic Todo List with useOptimistic
Show a new todo immediately while the asynchronous save operation completes in the background.
'use client';
import { startTransition, useOptimistic, useState } from 'react';
type Todo = {
id: string;
text: string;
pending?: boolean;
};
type Props = {
initialTodos: Todo[];
createTodo: (text: string) => Promise<Todo>;
};
React Form Validation with useActionState
Manage form validation, submission status, and server-style action results with React useActionState.
'use client';
import { useActionState } from 'react';
type FormState = {
message: string;
errors: {
email?: string;
};
};
const initialState: FormState = {
message: '',
errors: {},
};
async function subscribe(
previousState: FormState,
PHP Read JSON Request Body
Read and validate a JSON request body in PHP.
<?php
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);
if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON body.']);
exit;
}
Card Grid with Equal Height Cards
Create a responsive Bootstrap card grid where cards keep equal height.
<div class="row g-4">
<div class="col-md-6 col-lg-4">
<div class="card h-100">
<div class="card-body d-flex flex-column">
<h5 class="card-title">Feature title</h5>
Offcanvas Sidebar Layout
Open a mobile-friendly offcanvas sidebar with Bootstrap.
<button class="btn btn-outline-secondary" data-bs-toggle="offcanvas" data-bs-target="#accountMenu">
Menu
</button>
<div class="offcanvas offcanvas-start" tabindex="-1" id="accountMenu">
<div class="offcanvas-header">
Responsive Navbar Starter
A simple Bootstrap responsive navbar with collapse behavior.
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container">
<a class="navbar-brand" href="/">CodShot</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav">
Bootstrap Modal Form Skeleton
A small Bootstrap 5 modal with a form and submit button.
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newItemModal">
New item
</button>
<div class="modal fade" id="newItemModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
Bootstrap Toast Notification
Show a Bootstrap 5 toast message from JavaScript.
<button class="btn btn-primary" id="showToastBtn">Show toast</button>
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="demoToast" class="toast" role="status" aria-live="polite" aria-atomic="true">
<div class="toast-header">
Save UI State to localStorage
Remember a simple UI preference in localStorage.
const checkbox = document.querySelector('#compactMode');
const savedValue = localStorage.getItem('compactMode');
checkbox.checked = savedValue === '1';
document.body.classList.toggle('compact', checkbox.checked);
checkbox.addEventListener('change', () => {
Fetch JSON with Error Handling
Fetch JSON data and handle HTTP errors cleanly.
async function loadProfile() {
const response = await fetch('/api/profile');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return await response.json();
}
loadProfile()
Simple Form Validation
Validate a small form before submitting it.
const form = document.querySelector('#contactForm');
const emailInput = document.querySelector('#email');
const messageBox = document.querySelector('#formMessage');
form.addEventListener('submit', (event) => {
messageBox.textContent = '';
Event Delegation for Buttons
Handle clicks for many dynamic buttons with one event listener.
const list = document.querySelector('#todoList');
list.addEventListener('click', (event) => {
const button = event.target.closest('[data-action]');
if (!button) return;
const item = button.closest('.todo-item');
Toggle Class on Click
Toggle a CSS class on an element when a button is clicked.
const button = document.querySelector('#menuButton');
const menu = document.querySelector('#menu');
button.addEventListener('click', () => {
menu.classList.toggle('is-open');
});
Password Hash and Verify
Hash a password and verify it later with PHP built-in helpers.
<?php
$password = $_POST['password'] ?? '';
$hash = password_hash($password, PASSWORD_DEFAULT);
// Later, during login:
$valid = password_verify($password, $hash);
if ($valid) {
echo 'Password is correct';
} else {
echo 'Invalid password';
}
Toggle Dark Mode Class
A tiny dark mode toggle that stores the selected mode in localStorage.
const toggleButton = document.querySelector('[data-theme-toggle]');
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.documentElement.classList.add('dark');
}
toggleButton?.addEventListener('click', () => {
Fade In Utility Class
A reusable CSS fade-in animation utility class.
.fade-in {
animation: fade-in 300ms ease both;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}