Home > Mobile >  How to get current 'page' and pass as param in React Router v6
How to get current 'page' and pass as param in React Router v6

Time:01-07

How can I get the current "page", which is ":name" below in the Route, and pass that as a prop to the <Food> component? For example, if I'm on "/food/egg", I should be passing "egg"` to the component. I cannot find the answer with so many versions out there.

import React, { Component } from 'react';
import "./App.css";
import Food from './Food';
import { Routes, Route} from 'react-router-dom';

export default class App extends Component {
  render() {
    return (
      <div className="App">
        <Routes>
          <Route path="/food/:name" element={<Food name= 
 {something here?} />} />
        </Routes>
      </div>
    )
  }
}

CodePudding user response:

I am not sure how to pass that as a prop. But I can help you with getting the value from url in your destination route, i.e.,'/food/:name'

UseLocation is the hook that will help you achieve this in react router v6. It will get you the current url you are at. Once you get it, you could split it using the split function and extract the information you need from the url.

The code will go something like this:

First the import statement

import { useLocation } from 'react-router-dom'

Then the code inside the main function


const location = useLocation()

const name = location.pathname.split('/')[2]

In the split function pass in the index value of the ':name' with respect to the url

PS: This is my first answer here. Hope it helps!

CodePudding user response:

From react router docs:

import * as React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';

function ProfilePage() {
  // Get the userId param from the URL.
  let { userId } = useParams();
  // ...
}

function App() {
  return (
    <Routes>
      <Route path="users">
        <Route path=":userId" element={<ProfilePage />} />
        <Route path="me" element={...} />
      </Route>
    </Routes>
  );
}

So you just need to use the useParams hook which returns an object like { id: "1234", name: "John Doe" }.

  • Related