How to navigate to another page in React.js?

Member

by lily , in category: Javascript , a year ago

How to navigate to another page in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , a year ago

@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:

  1. Install React Router: npm install react-router-dom
  2. 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';
  3. Set up routing: Wrap your app's component inside the Router component. This sets up the routing functionality in your application. function App() { return ( ); }
  4. 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 ( ); }
  5. 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 ( ); }
  6. 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.