Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  56] [ 5]  / answers: 1 / hits: 39752  / 6 Years ago, sat, april 28, 2018, 12:00:00

i'm doing the project and i need to create some routes with React Router. My project is:
enter



Each square has a id 200and 201, and each turn that i to click i want to go for route like: http://localhost:3000/user/200 or http://localhost:3000/user/201 and when to go for that route, i want it to appear in the body 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??


More From » reactjs

 Answers
24

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


[#54549] Tuesday, April 24, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrettw

Total Points: 300
Total Questions: 98
Total Answers: 103

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;