How to use React Router with match.params?
31,388
At first you didn't setup your router correctly
App.js
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
class App extends React.Component {
render () {
return (
<Router>
<Home>
<Switch>
<Route path='/user/:token' component={Body} />
</Switch>
</Home>
</Router>
)
}
}
Home.js - now you are wrapping router inside children
class Home extends React.Component {
render () {
return (<div className='home' >
<Header />
{this.props.children} {/* This line will render router children which will be Body */}
</div>
)
}
}
Body.js
Inside body you will now receive this.props.match.params
I think you will figure out by yourself
Author by
Jota
Updated on April 29, 2020Comments
-
Jota about 4 years
i'm doing the project and i need to create some routes with React Router. My project is:
Each square has a id
200
and201
, and each turn that i to click i want to go for route like:http://localhost:3000/user/200
orhttp://localhost:3000/user/201
and when to go for that route, i want it to appear in thebody
"User 200"
or"User201"
, i read the documentation but did not understand..My
APP.JS
:import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import './App.css'; import Home from './Home'; const App = () => ( <Router> <Home/> </Router> ); export default App;
My
HOME.JS
:import React from 'react'; import Header from './Header'; import Body from './Body'; import './Home.css'; class Home extends React.Component { render() { return ( < div className = 'home' > < Header / > < Body / > < /div> ) } } export default Home;
My
BODY.JS
:import React from 'react'; import './Body.css'; import axios from 'axios'; import { Link } from "react-router-dom"; class Body extends React.Component { constructor() { super(); this.state = { employee: [], } } componentDidMount() { axios.get('http://127.0.0.1:3004/employee').then( response => this.setState({ employee: response.data }) ) } getName = () => { const { employee } = this.state; return employee.map(name => < Link className = 'link' to = '/user' > < div key = { name.id } className = 'item' > < img className = 'img' src = { `https://picsum.photos/${name.name}` } > < /img> <h1 className='name'> {name.name} </h 1 > < /div> </Link > ) } render() { return ( < div className = 'body' > { this.getName() } < /div> ) } } export default Body;
Someone would can help me please??