In path /user
, there is a list of users
When I click the name button, it will go to /user/:id
, which will use UserProfile
component
App.js
import "./styles.css";
import { Route, useHistory, withRouter } from "react-router-dom";
import Users from "./Users";
import UserProfile from "./UserProfile";
function App() {
let history = useHistory();
function handleClick() {
history.push("/user");
}
return (
<div className="App">
<button
onClick={() => {
handleClick();
}}
>
Click to change path
</button>
<Route exact path="/user" component={Users} />
<Route path="/user/:id" component={UserProfile} />
</div>
);
}
export default withRouter(App);
Users.js
const users = [
{ id: 1, name: "Tom" },
{ id: 2, name: "Ken" }
];
export default function Users() {
return (
<div className="App">
<h1>User List</h1>
{users.map((user) => {
return (
<div>
<button>{user.name}</button>
</div>
);
})}
</div>
);
}
UserProfile.jsx
// how to get the user object/id here?????
export default function UserProfile() {
return (
<div className="App">
<h1>User Profile</h1>
<p>I am user xxx</p>
</div>
);
}
On this stage, I am thinking the best practise to access to single user component.
Any suggestion?
Codesandbox
https://codesandbox.io/s/shy-butterfly-6ezgi?file=/src/Users.jsx:0-607