1

I have one component, which displays different content in dependence of a state. The state is defined in the component and used in the first render, which works properly. After that each component which is rendered inside the component sets another state onclick, which is no problem, because i could just pass the function to the component.

function Modules(props) {
  const [state, setState] = useState(props.state);
  //use location to get the state from the previous page
  const location = useLocation();

  //rerender the page when the state changes
  React.useEffect(() => {
    setState(location.state);
    setState(props.state);
  }, [location.state, props.state]);

  const handleClick = (e) => {
    console.log(e);
    console.log(location);
    setState({ currentComponent: e });
  };

  const modules = [];

  const projects = [];

  return (
    <div>
      {state.currentComponent === "chooseMod" && (
        <ModuleList modules={modules} setState={handleClick} />
      )}
      {state.currentComponent === "chooseProj" && (
        <ProjectList projects={projects} setState={handleClick} />
      )}
      {state.currentComponent === "setupMod" && (
        <ModSetupModal setState={handleClick} />
      )}
    </div>
  );
}

export default Modules;

Now I have a navigation which should set back the state when its clicked. This isn't working like expected. The useEffect never gets triggered.

This is how the part of my navigation which should set back the state looks like:

<Link to={{ pathname: "/", state: { currentComponent: "chooseMod" },}}>

I tried several different ways to achieve this but I always get a state: null in the location object. I'm glad for any ideas and impressions, thanks!

RubenSmn
  • 4,091
  • 2
  • 5
  • 24
gmad
  • 138
  • 9

2 Answers2

0

The state parameter in the location pathname excepts and object and hence you can pass as many values as you need by passing then as an object like

0

I finally got it myself. I think I was sending the state the wrong way in the link to. After changing it to this, I'm receiving the state correctly:

<Link to="/" state={{ currentComponent: "chooseMod" }}>

Maybe anyone can explain, why my first version didn't work?

gmad
  • 138
  • 9
  • 1
    The first version didn't work because it wasn't using the APIs/syntax of the current version of `react-router` you have installed. Where state is passed in the `Link` component was a breaking change between RRD v5 and v6. – Drew Reese Jan 20 '23 at 20:03
  • 1
    Thanks for the explanation! That explains, why I found examples all over the internet this way and it still didn't work in my case. ;) – gmad Jan 20 '23 at 20:50