11.22 Understanding Nested Routes
Blog.js
Blog.js
// import axios from "axios";
import React, { Component } from "react";
import { NavLink, Route, Switch } from "react-router-dom";
import "./Blog.css";
import NewPost from "./NewPost/NewPost";
import Posts from "./Posts/Posts";
class Blog extends Component {
render() {
return (
<div className="Blog">
<header>
<nav>
<ul>
<li>
<NavLink
to="/posts/"
exact
activeClassName="my-active"
activeStyle={{
color: "#fa923f",
textDecoration: "underline",
}}
>
Posts
</NavLink>
</li>
<li>
<NavLink
to={{
pathname: "/new-post",
hash: "#submit",
search: "?quick-submit=true",
}}
>
New Post
</NavLink>
</li>
</ul>
</nav>
</header>
{/* <Route path="/" exact render={() => <h1>Home</h1>} />
<Route path="/" render={() => <h1>Home2</h1>} /> */}
<Switch>
<Route path="/new-post" component={NewPost} />
<Route path="/posts" component={Posts} />
</Switch>
</div>
);
}
}
export default Blog;
Posts.js
Posts.js
import React, { Component } from "react";
import { Route } from "react-router-dom";
import axios from "../../../axios";
import Post from "../../../components/Post/Post";
import FullPost from "../FullPost/FullPost";
import "./Posts.css";
class Posts extends Component {
state = {
posts: [],
};
componentDidMount() {
console.log(this.props);
axios
.get("/posts")
.then((response) => {
const posts = response.data.slice(0, 4);
const updatedPosts = posts.map((post) => {
return {
...post,
author: "Pash",
};
});
this.setState({ posts: updatedPosts });
// console.log(response);
})
.catch((error) => {
console.log(error);
// this.setState({ error: true });
});
}
postSelectedHandler = (id) => {
// this.props.history.push({ pathname: "/posts/" + id });
this.props.history.push("/posts/" + id);
};
render() {
let posts = <p style={{ textAlign: "center" }}>Something went wrong!</p>;
if (!this.state.error) {
posts = this.state.posts.map((post) => {
return (
// <Link to={"/posts/" + post.id} key={post.id}>
<Post
key={post.id}
title={post.title}
author={post.author}
clicked={() => this.postSelectedHandler(post.id)}
/>
// </Link>
);
});
}
return (
<div>
<section className="Posts">{posts}</section>
<Route
path={this.props.match.url + "/:id"}
exact
component={FullPost}
/>
</div>
);
}
}
export default Posts;