Set Up Your React Project
Open your terminal and run the following commands:
npx create-react-app blog-platform
cd blog-platform
Step 2: Install React Router
You’ll need React Router for navigation:
npm install react-router-dom
Step 3: Create Blog Components
Replace the content of src/App.js
with the following code:
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import './App.css';
const postsData = [
{
id: 1,
title: 'First Blog Post',
content: 'This is the content of the first blog post.',
},
{
id: 2,
title: 'Second Blog Post',
content: 'This is the content of the second blog post.',
},
{
id: 3,
title: 'Third Blog Post',
content: 'This is the content of the third blog post.',
},
];
const Home = () => (
<div>
<h2>Blog Posts</h2>
<ul>
{postsData.map((post) => (
<li key={post.id}>
<Link to={`/post/${post.id}`}>{post.title}</Link>
</li>
))}
</ul>
</div>
);
const Post = ({ match }) => {
const post = postsData.find((p) => p.id === parseInt(match.params.id));
return (
<div>
{post ? (
<>
<h2>{post.title}</h2>
<p>{post.content}</p>
<Link to="/">Go Back</Link>
</>
) : (
<h2>Post not found</h2>
)}
</div>
);
};
const App = () => {
return (
<Router>
<div className="App">
<header className="header">
<h1>Blog Platform</h1>
<nav>
<Link to="/">Home</Link>
</nav>
</header>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/post/:id" component={Post} />
</Switch>
</div>
</Router>
);
};
export default App;
Step 4: Style Your Blog Platform
Open src/App.css
and add some basic styles:
body {
margin: 0;
font-family: Arial, sans-serif;
}
.App {
text-align: center;
padding: 20px;
}
.header {
background-color: #282c34;
color: white;
padding: 20px;
}
.header nav a {
margin: 0 15px;
color: white;
text-decoration: none;
}
.header nav a:hover {
text-decoration: underline;
}
h2 {
margin-top: 20px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
}
footer {
margin-top: 40px;
padding: 20px 0;
background-color: #f1f1f1;
}
Step 5: Run Your Application
In the terminal, run:
npm start
Leave a Reply