1

Am trying to edit post by it's id and I would like pass the id a a prop to the EditPost component how do I go about it?

  render() {
    return (
      <Router>
      <Switch >
        <Route path="/edit/:id">
          <EditPost index={/*what do I do here?*/} />
        </Route>
      </Switch>
      </Router>
    );
  }
iamafasha
  • 848
  • 10
  • 29
  • See [this answer here](https://stackoverflow.com/questions/35352638/react-how-to-get-parameter-value-from-query-string). You get it from props – Tasos Feb 19 '20 at 14:11
  • Does this answer your question? [React - How to get parameter value from query string](https://stackoverflow.com/questions/35352638/react-how-to-get-parameter-value-from-query-string) – jmargolisvt Feb 19 '20 at 14:20
  • I specifically wanted to do it in the jsx `` – iamafasha Feb 19 '20 at 17:23

2 Answers2

2

In your EditPost component you can do it like this:

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

const EditPost = () => {
  const params = useParams();

  return <p>Your Post ID is: {params.id}</p>  
}

export default EditPost;

And make your route as:

<Route path="/edit/:id">
  <EditPost />
</Route>

Hope this works for you.

Muhammad Zeeshan
  • 4,608
  • 4
  • 15
  • 41
1

If you write the component with class component, you can use next approach. Here is the component

const EditPost = ({ match }) => {
  let { id } = match.params
  // ...
}

or the same with hook:

const EditPost = () => {
  let { id } = useParams();
  // ...
}

And then in router you can use it like this:

<Router>
  <div>
    <Switch>
      <Route path="/blog/:slug" component={BlogPost} />
    </Switch>
  </div>
</Router>