@lily
In React.js, you can navigate to another page using react-router-dom library which allows you to manage routing in your application. Here is a step-by-step guide on how to navigate to another page using React Router:
- Install React Router:
npm install react-router-dom
- Import necessary components:
In the file where you want to use the routing functionality, import the necessary components from react-router-dom:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
- Set up routing:
Wrap your app's component inside the Router component. This sets up the routing functionality in your application.
function App() {
return (
);
}
- Define routes:
Define the routes you want to navigate to using the Route component. Each Route component represents a different page in your application.
function App() {
return (
);
}
- Add navigation links:
Add navigation links to your components using the Link component. This allows users to navigate to different pages in your application.
function App() {
return (
);
}
- Handle navigation programmatically:
If you want to navigate programmatically, you can use the history object from the react-router-dom package. The useHistory hook is a simple way to access the history object.
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleNavigation = () => {
history.push('/about');
};
return (
);
}
By following these steps, you can navigate to different pages in your React.js application.