Hello.
I’m trying (and almost succeeding) in getting React Router DOM working - I’m using React Create App to build my App.
I’ve got top level pages working (Home, About, Topics) but am having a problem with individual Topic listed on the main Topics page.
Here’s the code:
Topics.js
import React from 'react'
import { BrowserRouter as Router,Route, Link } from "react-router-dom"
import Topic from "./Topic"
function Topics({ match }){
return(
<Router>
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${match.url}/components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>Props v. State</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic} />
<Route path={match.url} render={() => <h3>Please select a topic.</h3>} />
</div>
</Router>
)
}
export default Topics
Topic.js
import React from 'react'
function Topic({match}){
return(
<div>
<h3>{match.params.topicId}</h3>
</div>
)
}
export default Topic
When I land on the Topics page there are links to each individual topic:
and when I click on a topic link, e.g. ‘Rendering with React’ I get the ‘rendering’ page:
The word ‘rendering’ in bold is output via <h3>{match.params.topicId}</h3>
in Topic.js and is just the url fragment of the targeted page.
What I’ve been struggling with for many hours is how to get any specific content to display on each of the three pages using some kind of conditional statement, something like (pseudo-code):
function Topic({match}){
if(path === topics/rendering) {
return (
<div>
<h3>{match.params.topicId}</h3>
<p>Rendering content...</p>
</div>
)
} else if(path === topics/components) {
return (
<div>
<h3>{match.params.topicId}</h3>
<p>Components content...</p>
</div>
)
} else if(path === topics/props-v-state) {
return (
<div>
<h3>{match.params.topicId}</h3>
<p>Props V State content...</p>
</div>
)
}
}
export default Topic
If I’m not being clear, please say and I will try and supply more details.
Hope someone can point me in the right direction!
Chris