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!