2

I am developing a FunctionalComponentthat will render a list of items, in Ionic with React. The component will be reused for every type of item's status. I am passing the item's status as a url-param.

I want to get the url-paramand display it as the List Title and use it to call the API for the matched items. Rendering the List-Componentthe url param's matchrenders as undefined.

How can I get the url param in the Component?

Link to the List-Page at Dashboard.tsx:

<IonCard className="card-body" href="/list/onschedule">

App.tsx:

<IonRouterOutlet>
    <Route exact path="/login" component={Login} />
    <Route exact path="/" render={() => <Redirect to="/dashboard" />} />
    <PrivateRoute path="/dashboard" component={Dashboard} exact={true} />
    <PrivateRoute path="/list/:status" component={List} />
</IonRouterOutlet>

In the PrivateRoutecomponent I placed a console.log for the props and it's getting the param: enter image description here

List.tsx:

interface StatusMatchProps extends RouteComponentProps<{
  status: string;
}> {}

const List: React.FunctionComponent<StatusMatchProps> = ({match}) => {
  console.log("match: " + match)

  return (
    <>
      <IonTitle>{match.params.status}</IonTitle>
  );
};

Chrome's console output:

enter image description here

MohammedAli
  • 2,361
  • 2
  • 19
  • 36
solracid
  • 413
  • 5
  • 21
  • 1
    __Rendering the List-Componentthe url param's matchrenders as undefined.__ How is the list component rendered? It is rendered as standalone component or rendered when the path matches with the path of the PrivateRoute that is declared? – Oluwafemi Sule Dec 26 '19 at 12:43

1 Answers1

0

The issue was in the PrivateRouteComponent not passing the props. This is the working version of the Component:

interface PrivateRouteProps extends RouteProps {
  component: any
}

export const PrivateRoute: FunctionComponent<PrivateRouteProps> = ({ component: Component, ...rest }) => (

<Route {...rest} render={props => {
    const currentUser: string | null  =  localStorage.getItem("userID");

    if (!userID) {
        // not logged in so redirect to login page with the return url
        return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    }

    // authorised so return component
    return <Component {...props} />
  }} />
); 
solracid
  • 413
  • 5
  • 21