React Router Navigation: Passing Parameters
In React, you can use React Router for routing navigation and passing parameters. Here is the method for routing navigation and passing parameters using React Router:
- To install React Router: First, you need to install the React Router library. You can use the following command to install React Router:
npm install react-router-dom
- A browser router
- Router that uses hash symbol in the URL for navigation
- Path
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Router>
);
}
- “Connection”
- add the current page to the browsing history
- Utilize the Link component:
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
- Navigate using the history.push method:
import { useHistory } from 'react-router-dom';
function Home() {
const history = useHistory();
const handleClick = () => {
history.push('/about');
};
return (
<div>
<button onClick={handleClick}>Go to About</button>
</div>
);
}
- Path
- translate, depict, interpret
- Parameters in the routing path.
<Route path="/user/:id" component={User} />
In the User component, you can access the passed parameter through props.match.params.id.
- Use the render attribute.
<Route path="/user" render={(props) => <User {...props} userId={123} />} />
In the User component, you can access the passed parameter through props.userId.
These are the basic methods for routing and passing parameters using React Router. Depending on specific needs, more advanced features such as nested routing and route guards can also be used.