I am new here and writing to ask a problem about React's router. I have Googled for over two hours but cannot find a working solution.
Basically, I am writing a website that can show a list of articles. There is a button called "Articles" on the homepage. Once we click it, the router will work and go to page "/articles", like the codes below show.
File A:
import React, { Component } from 'react';
import {BrowserRouter, Route, Link, Switch} from 'react-router-dom';
class A extends Component {
constructor(props) {
super(props);
}
render() {
return (
<BrowserRouter>
<div>
<div>
<button><Link to = "/articles"> Articles </Link></button>
</div>
<Switch>
<Route exact path = '/articles' render = {() => <B />}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
The list of articles will be shown by the component B. I designed that component B will have two situations. First, by default, when we click the button in component A, the URL is "/articles", and then a list of article shows. Second, if we click any of the article title, the URL will be changed to "articles/articleID", and the component will show the detail of that articleID.
File B:
import React, {Component} from 'react';
import {BrowserRouter, Route, Link, Switch} from 'react-router-dom';
class B extends Component {
constructor(props) {
super(props);
}
render() {
return (
<BrowserRouter>
<div>
<Switch>
<Route exact path = "/articles" render = {(props) => <Articles {...props} />}/>
<Route path = "/articles/:articleId" render = {() => <ArticleDetail />}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
Now my problem is, when in the page of article details (when the page URL is "/articles/articleId"), I can click the "Articles" button in component A, and the URL will be changed to "/articles", but the page will not be rendered, which means, I will still on the page of article details, instead of returning to the page of a list of articles.
If my description confuses you, please ask me! Thank you for your help!