SmartCodingTips

📝 Blog App in React

A Blog App lets you display and manage blog posts. In this project, we’ll create a simple version that loads posts, displays them, and uses routing for individual blog detail pages.


📦 1. Setup Routes and Pages


// App.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import BlogDetail from './pages/BlogDetail';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/blog/:slug" element={<BlogDetail />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

📃 2. Create Sample Blog Data


// data.js
export const blogPosts = [
  {
    slug: 'react-hooks-intro',
    title: 'Introduction to React Hooks',
    content: 'Hooks let you use state and other features without writing a class...',
  },
  {
    slug: 'tailwind-with-react',
    title: 'Using Tailwind CSS in React',
    content: 'Tailwind makes it easy to style your React components...',
  }
];

🏠 3. Home Page with Blog List


// Home.jsx
import { Link } from 'react-router-dom';
import { blogPosts } from '../data';

function Home() {
  return (
    <div className="space-y-4">
      <h2 className="text-2xl font-bold">📝 Blog Posts</h2>
      {blogPosts.map((post) => (
        <div key={post.slug} className="p-4 border rounded dark:border-gray-700">
          <h3 className="text-xl font-semibold">{post.title}</h3>
          <Link
            to={`/blog/${post.slug}`}
            className="text-blue-600 hover:underline dark:text-blue-400"
          >
            Read More →
          </Link>
        </div>
      ))}
    </div>
  );
}

export default Home;

📄 4. Blog Detail Page


// BlogDetail.jsx
import { useParams } from 'react-router-dom';
import { blogPosts } from '../data';

function BlogDetail() {
  const { slug } = useParams();
  const post = blogPosts.find((b) => b.slug === slug);

  if (!post) return <p>Post not found</p>;

  return (
    <div className="space-y-4">
      <h2 className="text-2xl font-bold">{post.title}</h2>
      <p>{post.content}</p>
    </div>
  );
}

export default BlogDetail;

📋 Summary

  • Used react-router-dom for dynamic routing
  • Stored blog data in a simple array
  • Created list & detail pages with route parameters
  • Expandable to use APIs or markdown files later