All types of routing in React

In React applications, there are multiple ways to handle routing and navigating from one page to another. The choice of routing method often depends on the specific needs and complexity of your application. Here are some common ways to perform routing in a React application.

1. React Router DOM:

  • It is the most popular and widely used library for managing routing in React applications.
  • It provides a declarative way to define routes using components and allows navigation between different parts of your application.
  • You can use BrowserRouter or HashRouter to set up routing in your application.

import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <Route path="/page1" component={Page1} /> <Route path="/page2" component={Page2} /> {/* ... */} </Router> ); }

2. Conditional rendering:

  • Instead of using a dedicated routing library, you can conditionally render different components based on the state or props of your main component.

function App() { const currentPage = 'page1'; return ( <div> {currentPage === 'page1' && <Page1 />} {currentPage === 'page2' && <Page2 />} {/* ... */} </div> ); }


3. Context API:

  • You can use React's context API to manage the current page or root at a higher level of your component tree and pass it to child components.

const PageContext = React.createContext(); function App() { const [currentPage, setCurrentPage] = useState('page1'); return ( <PageContext.Provider value={{ currentPage, setCurrentPage }}> <Page1 /> <Page2 /> {/* ... */} </PageContext.Provider> ); }


4. Hooks (usage history, location usage etc.):

  • React Router DOM provides hooks like useHistory and useLocation that allow you to directly interact with history and location objects.

import { useHistory } from 'react-router-dom'; function MyComponent() { const history = useHistory(); const handleClick = () => { // Navigate to a different page history.push('/newPage'); }; return ( <button onClick={handleClick}> Go to New Page </button> ); }


5. Third party libraries:

  •  React Router In addition to the DOM, there are other third-party libraries that provide routing capabilities in React, such as Reach/Router, Wouter, and more.

import { Router, Link } from 'wouter'; function App() { return ( <Router> <Link href="/page1">Page 1</Link> <Link href="/page2">Page 2</Link> </Router> ); }


Each of these methods has its uses, and the choice depends on factors such as project requirements, preferences, and specific features offered by methods or libraries. React Router DOM is a popular choice due to its feature-rich capabilities and active community support.

Post a Comment

1 Comments