Explore

Explore snippets

Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.

Public snippets by CodShot user
Clear
105 public snippets
Open
TSX
Public

Dynamic Page with notFound

Render the nearest not-found UI when a requested App Router record does not exist.

TSX Preview
// 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;
#nextjs #app-router #routing #error-handling
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #217
Open
TSX
Public

Lazy Component Loading with Suspense

Load a large component only when it is rendered and show a fallback during download.

TSX Preview
'use client';

import { lazy, Suspense, useState } from 'react';

const AnalyticsChart = lazy(
  () => import('./analytics-chart'),
);

export function AnalyticsPanel() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <section>
      <button
#react #suspense #lazy-loading #performance
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #216
Open
TSX
Public

Accessible Form Fields with useId

Generate stable IDs for reusable form controls and accessible help text.

TSX Preview
import { useId } from 'react';

type TextFieldProps = {
  label: string;
  name: string;
  helpText?: string;
};

export function TextField({
  label,
  name,
  helpText,
}: TextFieldProps) {
  const inputId = useId();
  const helpId = `${inputId}-help`;
#react #accessibility #form #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #215
Open
TSX
Public

Non-Blocking Tabs with useTransition

Switch expensive tab content without blocking urgent UI updates.

TSX Preview
'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');
#react #hooks #performance #ui
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #214
Open
TSX
Public

Deferred Search Results with useDeferredValue

Keep a search input responsive while a larger result list updates at lower priority.

TSX Preview
'use client';

import { useDeferredValue, useMemo, useState } from 'react';

type Product = {
  id: number;
  name: string;
};

export function ProductSearch({ products }: { products: Product[] }) {
  const [query, setQuery] = useState('');
#react #hooks #search #performance
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #213
Open
TSX
Public

Optimistic Todo List with useOptimistic

Show a new todo immediately while the asynchronous save operation completes in the background.

TSX Preview
'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 #hooks #state #optimistic-ui
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #212
Open
TSX
Public

React Form Validation with useActionState

Manage form validation, submission status, and server-style action results with React useActionState.

TSX Preview
'use client';

import { useActionState } from 'react';

type FormState = {
  message: string;
  errors: {
    email?: string;
  };
};

const initialState: FormState = {
  message: '',
  errors: {},
};

async function subscribe(
  previousState: FormState,
#react #hooks #form #validation
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #211
Open
PHP
Public

cURL GET Request in PHP

Call an external API with cURL and decode the JSON response.

PHP Preview
<?php

$ch = curl_init('https://api.example.com/items');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
]);

$responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
#php #curl #api #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #128
Open
PHP
Public

PHP Read JSON Request Body

Read and validate a JSON request body in PHP.

PHP Preview
<?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;
}
#php #api #json #validation
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #127
Open
PHP
Public

PHP JSON Response Helper

Return a JSON response from a small PHP endpoint.

PHP Preview
<?php

function json_response(array $payload, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
#php #api #json #response
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #126
Open
JavaScript
Public

Fetch POST JSON Request

Send JSON data to a backend endpoint with fetch.

JavaScript Preview
async function createNote(note) {
    const response = await fetch('/api/notes', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(note)
    });

    if (!response.ok) {
#api #javascript #post #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #125
Open
JavaScript
Public

Fetch GET Request

Load JSON from an API endpoint with async and await.

JavaScript Preview
async function searchSnippets(query) {
    const url = `/api/snippets?search=${encodeURIComponent(query)}`;
    const response = await fetch(url);

    if (!response.ok) {
        throw new Error('Search request failed.');
    }
#api #javascript #fetch #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #124
Open
HTML / Markup
Public

Card Grid with Equal Height Cards

Create a responsive Bootstrap card grid where cards keep equal height.

HTML / Markup Preview
<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>
#bootstrap #card #grid #responsive
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #123
Open
HTML / Markup
Public

Offcanvas Sidebar Layout

Open a mobile-friendly offcanvas sidebar with Bootstrap.

HTML / Markup Preview
<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">
#bootstrap #offcanvas #sidebar #responsive
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #122
Open
HTML / Markup
Public

Responsive Navbar Starter

A simple Bootstrap responsive navbar with collapse behavior.

HTML / Markup Preview
<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 #navbar #responsive #layout
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #121
Open
HTML / Markup
Public

Bootstrap Modal Form Skeleton

A small Bootstrap 5 modal with a form and submit button.

HTML / Markup Preview
<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 #modal #form #ui
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #120
Open
HTML / Markup
Public

Bootstrap Toast Notification

Show a Bootstrap 5 toast message from JavaScript.

HTML / Markup Preview
<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">
#bootstrap #toast #ui #javascript
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #119
Open
JavaScript
Public

Save UI State to localStorage

Remember a simple UI preference in localStorage.

JavaScript Preview
const checkbox = document.querySelector('#compactMode');
const savedValue = localStorage.getItem('compactMode');

checkbox.checked = savedValue === '1';
document.body.classList.toggle('compact', checkbox.checked);

checkbox.addEventListener('change', () => {
#javascript #localstorage #ui #state
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #118
Open
JavaScript
Public

Fetch JSON with Error Handling

Fetch JSON data and handle HTTP errors cleanly.

JavaScript Preview
async function loadProfile() {
    const response = await fetch('/api/profile');

    if (!response.ok) {
        throw new Error(`Request failed: ${response.status}`);
    }

    return await response.json();
}

loadProfile()
#javascript #fetch #json #error-handling
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #117
Open
JavaScript
Public

Simple Form Validation

Validate a small form before submitting it.

JavaScript Preview
const form = document.querySelector('#contactForm');
const emailInput = document.querySelector('#email');
const messageBox = document.querySelector('#formMessage');

form.addEventListener('submit', (event) => {
    messageBox.textContent = '';
#javascript #form #validation #frontend
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #116
Open
JavaScript
Public

Event Delegation for Buttons

Handle clicks for many dynamic buttons with one event listener.

JavaScript Preview
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');
#javascript #dom #events #performance
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #115
Open
JavaScript
Public

Toggle Class on Click

Toggle a CSS class on an element when a button is clicked.

JavaScript Preview
const button = document.querySelector('#menuButton');
const menu = document.querySelector('#menu');

button.addEventListener('click', () => {
    menu.classList.toggle('is-open');
});
#javascript #dom #ui #beginner
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #114
Open
PHP
Public

Basic Upload Validation

Validate upload error, size, and MIME type before accepting a file.

PHP Preview
<?php

$file = $_FILES['avatar'] ?? null;

if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    throw new RuntimeException('Upload failed.');
}

if ($file['size'] > 2 * 1024 * 1024) {
    throw new RuntimeException('The file is too large.');
}
#php #upload #validation #security
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #113
Open
PHP
Public

Safe Redirect Allow List

Redirect only to known internal paths instead of trusting user input.

PHP Preview
<?php

$allowedRedirects = [
    '/my-dashboard',
    '/my-workspace',
    '/my-billing',
];

$next = $_GET['next'] ?? '/my-dashboard';

if (!in_array($next, $allowedRedirects, true)) {
    $next = '/my-dashboard';
}

header('Location: ' . $next);
exit;
#php #redirect #security #validation
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #112
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support