use React nested route, Home is the parent and News is the child. under root directory,there is "src" folder, in "src", is "pages" folder, in "pages", are "Home" and "News" folder. In "News", there is index.js:
Directory Structure :
| src/
| -- pages/
| ----- Home/
| --------index.js
| ----- News/
| --------index.js
| -- App.js
News/index.js
import React from 'react'
export default class News extends React.Component {
render(){
return(
<div style={{backgroundColor:'green',padding:10}}>
this is content of child subcomponent
</div>
)
}
}
Home/index.js
import React from 'react'
import {BrowserRouter as Router,Route,Routes} from 'react-router-dom'
import News from '../News'
export default class Home extends React.Component {
render(){
return(
<div style={{backgroundColor:'skyblue',padding:10}}>
home
<Routes>
<Route path = '/home/news' element={<News/>}></Route>
</Routes>
</div>
)
}
src/App.js
import './App.css';
import {BrowserRouter as Router,Route,Link,Routes} from 'react-router-dom'
import {Button} from 'antd-mobile'
import Home from './pages/Home'
import CityList from './pages/CityList'
import React from 'react';
function App() {
return (
<Router>
<div className="App">
<ul>
<li><Link to='/home'>home</Link></li>
<li><Link to='/citylist'>citylist</Link></li>
</ul>
<Routes>
<Route path='/home' element={<Home/>}/>
<Route path='/citylist' element = {<CityList/>}/>
</Routes>
</div>
</Router>
);
}
export default App;
when the program running, as the web site is http://localhost:3000/home,it is ok, but when I add news after the website, http://localhost:3000/home/news , the child component has not been shown correctly, that is no "this is content of child subcomponent" displayed, could you please tell me why and how to solve it.
I guess you are probably using react router 6. In that case you need to use Outlet in order to render nested child routes.
import React from "react";
import { BrowserRouter, Routes, Route, Link, Outlet } from "react-router-dom";
import "./styles.css";
function News() {
return (
<div style={{ backgroundColor: "green", padding: 10 }}>
this is content of child subcomponent
</div>
);
}
function Home() {
return (
<div style={{ backgroundColor: "skyblue", padding: 10 }}>
home
{
// Render child route.
}
<Outlet />
</div>
);
}
function CityList() {
return (
<div>
<p>City list</p>
</div>
);
}
export default function App() {
return (
<BrowserRouter>
<div className="App">
<ul>
<li>
<Link to="/home">home</Link>
</li>
<li>
<Link to="/citylist">citylist</Link>
</li>
</ul>
<Routes>
<Route path="/home" element={<Home />}>
{
// Nested Child Route.
}
<Route path="news" element={<News />} />
</Route>
<Route path="/citylist" element={<CityList />} />
</Routes>
</div>
</BrowserRouter>
);
}