Home > OS >  Sending parameter to Link to a Router component Reacts
Sending parameter to Link to a Router component Reacts

Time:02-12

Im currently trying to send a state from the Link component to the Router component.

The router component looks like this:

<Route
  exact
  path='/banner/edit/:id'
>
  {!user && <Redirect to="/login" />}
  {user && org && <EditBanner uid={user.uid} org={org} />}
</Route>

This component is only rendered when the user is not null, and when the org is not null.

The EditBanner has a state called: bannerTitle:

export const EditBanner = ({ uid, org }) => {

  // States
  const [bannerTitle, setBannerTitle] = useState(null);
  ...

And when I am using Link to go to the component, I want to pass in the bannerTitle as a property to set the state in the EditBanner component. However, this is not having any effect on the Component.

<Link
  to={{
    pathname: "/banner/edit/"   banner.id,
    state: { bannerTitle: "HELLO" }
  }}
>
  Edit
</Link>

Where can I get the passed props?

CodePudding user response:

You can use the useLocation hook which provides a location object which has state:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import {useLocation} from "react-router-dom";

export const EditBanner = ({ uid, org }) => {
  let location = useLocation();
  useEffect(() => {
    console.log(location.state);
  }, [location])

  // ...
}

Hopefully that helps!

  • Related