Home > Enterprise >  Use URL parameter as a prop in React
Use URL parameter as a prop in React

Time:06-01

I am trying to run an onLoad event to get data from my db. I need to use a url parameter as a the prop to do this with but can't figure out how to access it.

I am using react-router v6, although in my package.json it is called react-router-dom.

Here is my setup

index.js

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="/newrecipe" element={<RecipeForm />} />
      <Route path="/recipe/:name" element={<RecipeDBTest />} /> //relevant line
    </Routes>
  </BrowserRouter>

Then in RecipeDBTest.jsx I need to grab the final parameter from my url string that looks like this:

http://localhost:3000/recipe/toast

So I would grab toast from URL string and pass to server with a fetch request on the RecipeDBTest.jsx page.

Just hoping for some advice/guidance here.

CodePudding user response:

You can use useParams hook of react-router.

import {
  useParams
} from "react-router-dom";

function Child() {
  // We can use the `useParams` hook here to access
  // the dynamic pieces of the URL.
  let { name } = useParams();

  return (
    <div>
      <h3>Name: {name}</h3>
    </div>
  );
}

CodePudding user response:

      let name = this.props.match.params.name
   
  • Related