0
votes

I am not able to send the parameter through state using useHistory history.push method from react-router dom.

Now suppose I want to pass more than a string to the Paging component i.e. some props too.

My Paging Component which throws error for state value state is not defined

const PAGING = ({ location }) => {
    console.log(location);
    console.log(location.state);
    console.log(location.state.id);
return <div>Hello <div>}

History.push method in another component

    const handleDetails = (id,name) => {
        console.log(name)
        if (id) {
            return history.push({
                pathname: `/detailing/${name}`,
                state: { id }
             });
        } else {
          return history.push("/");
        }
        };

const Switch = () => {
    const { state: authState } = useContext(AuthContext)
    return (
        <div>
            <Router>
            <Switch>
           <ProtectedSystem
            path= "/detailing/:name"
            exact
            auth={authState.isAuthenticated}
            component={PAGING}
          /> 
           </Switch>
            </Router>
        </div>
    );

 const ProtectedSystem = ({auth , component: Component, ...rest}) =>{
    return(
        <Route 
        {...rest}
        render={() => auth ?  (<Component/>) : (<Redirect to = '/' /> )}
        />
    )
} 

If I use simple route without condition based its working fine

<Route path= "/detailing/:name" exact component={PAGING} /> 
2
What isn't working as expected? Or rather, what are you trying to do? The history.push with state appears to be correct. - Drew Reese
When my PAGING Component loads throws error for console.log(location.state); - Parth Tiwari
Ah, I see. @ShubhamKhatri has it, though I'd suggest refactoring the code a bit so ProtectedSystem always returns a Route or Redirect, i.e. move the auth context into it and determine which to return, the route props would still need to be piped through to them though. - Drew Reese

2 Answers

1
votes

You need to pass on the Route params to the rendered component so that it can use them

const ProtectedSystem = ({auth , component: Component, ...rest}) =>{
    return(
        <Route 
        {...rest}
        render={(routeParams) => auth ?  (<Component {...routeParams}/>) : (<Redirect to = '/' /> )}
        />
    )
} 
-1
votes

You can do this entirely with React hooks and pure functions, eg.

import React from 'react';
import { useHistory } from 'react-router-dom';

const ProtectedSystem = ({ auth }) => {
  const history = useHistory();
  if (!authUser) {
    history.push("/signin");
  }
  return (
    <div><h1>Authorized user</h1></div>
  )
}
export default ProtectedSystem