Home > OS >  How do I capture React Router dynamic parameters in the parent?
How do I capture React Router dynamic parameters in the parent?

Time:06-28

I want to be able to store the child's id in the parent component. However, I'm not sure how to do so. I know that I can call useParams() in the child, and then pass the id back to the parent, but this seems like a roundabout way to accomplish this.

<Route path="/project/:id" element={<Child />}>
</Route>

const childId = ???

CodePudding user response:

You can create a state in a parent component, send setState to the child and call setState in child component, after receiving id, using useParams();

Parent const [id, setId] = useState(''); <Route path="/project/:id" element={<Child setId={setId} />}> </Route>

Child

const {id} = useParams();
props.setId(id); // Or however you access props in your component
  • Related