chatblocks

Code Block

A syntax-highlighted code block component for displaying code snippets.

Examples

Basic Usage

A simple code block with syntax highlighting for TypeScript.

function greet(name: string) {
  return `Hello, ${name}!`;
}

const message = greet("World");
console.log(message);

With Toolbar

Code block with a toolbar the file name and a copy code button.

example.tsx
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';

interface User {
  id: number;
  name: string;
  email: string;
}

export function UserList() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await fetch('/api/users');
      const data = await response.json();
      setUsers(data);
    } catch (error) {
      console.error('Failed to fetch users:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div className="space-y-4">
      {users.map((user) => (
        <div key={user.id} className="p-4 border rounded">
          <h3>{user.name}</h3>
          <p>{user.email}</p>
        </div>
      ))}
    </div>
  );
}

Installation

npx shadcn@latest add "https://chatblocks.dev/r/code-block.json"