Home > Software design >  How to pass a prop Function in a Redirect in react
How to pass a prop Function in a Redirect in react

Time:01-15

I have a function that toggles a useState variable. I have a function that toggles the variable. In my App.js i have a Redirects to a component. I am unsure how to pass the prop function to the component though the Redirect. The Toggle Function i want to pass is called onToggle the function that does the toggling is called whichchoice. i have tried the following to no avail. Any help would be appreciated. ======== The App.js ========

<Switch>
          {getRoutes(routes)}
          <Redirect from="*" to="/dashboards/default" onToggle={whichchoice} />
</Switch>

======== The component dashboard/default =======

};
function Default(onToggle) {

return (
  <SuiBox mt={4} mb={1}>
            <SuiButton
              variant="gradient"
              color="info"
              size="large"
              fullWidth
              onClick={() => {
                onToggle();
              }}
            >
)

CodePudding user response:

      <Redirect from="*" to={{
        pathname: "/dashboards/default",
        state: { onToggle: whichchoice }
      }}/>

then in your default Component you access it:

console.log("onToggle",this.props.location.state.onToggle);}

CodePudding user response:

I guess you can access it using useLocation() hook. https://v5.reactrouter.com/web/api/Hooks/uselocation

I guess something like this:

function Default(onToggle) {
const location = useLocation() 
return (
  <SuiBox mt={4} mb={1}>
            <SuiButton
              variant="gradient"
              color="info"
              size="large"
              fullWidth
              onClick={() => {
                location.state?.onToggle();
              }}
            >
)
  •  Tags:  
  • Related