Working with Code Blocks

Working with Code Blocks

One of the most important features for a developer blog is proper code rendering. This post demonstrates how code blocks are rendered with syntax highlighting powered by PrismJS.

JavaScript Basics

#

Here is a simple function that greets a user:

function greet(name) {
  const message = `Hello, ${name}! Welcome to my blog.`;
  console.log(message);
  return message;
}

greet('World');

You can also use const and let for variable declarations instead of var. Inline code like console.log() is rendered with a distinct monospace style.

TypeScript Examples

#

TypeScript adds type safety on top of JavaScript:

interface BlogPost {
  id: string;
  title: string;
  slug: string;
  category: string[];
  isPublished: boolean;
  createdAt: Date;
}

function getPublishedPosts(posts: BlogPost[]): BlogPost[] {
  return posts
    .filter((post) => post.isPublished)
    .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
}

React JSX Component

#

Here is a typical React component written in JSX:

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div className="counter">
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

TypeScript + React (TSX)

#

Combining TypeScript with React gives you the best developer experience:

interface PostCardProps {
  title: string;
  description: string;
  date: string;
  category: string;
}

const PostCard = ({ title, description, date, category }: PostCardProps) => {
  return (
    <article className="post-card">
      <span className="category">{category}</span>
      <h3>{title}</h3>
      <p>{description}</p>
      <time dateTime={date}>{date}</time>
    </article>
  );
};

export default PostCard;

CSS Styling

#

Don't forget about styling your components:

.post-card {
  border-radius: 12px;
  padding: 1.5rem;
  background: var(--bg-secondary);
  transition: transform 0.2s ease;
}

.post-card:hover {
  transform: translateY(-4px);
}

All code blocks support syntax highlighting out of the box. The library uses PrismJS to detect the language and apply the appropriate color theme.