I've been running into an issue that's had me stum...
# help
a
I've been running into an issue that's had me stumped: I've been addng new
<UnauthenticatedRoute>
's, but for them if I pass in a
state
when I navigate to them with
react-router-dom
's
Link
, the
state
is stripped out. I know I need to change something here:
Copy code
<Route {...rest}>
      {!isAuthenticated ? (
        children
      ) : (
        <Redirect to={redirect === "" || redirect === null ? "/" : redirect} />
      )}
    </Route>
To pass the
state
in
<Link to={{ to="./classes/:id", state: { stuff: 'cool' }}}>
through. But, I haven't figured out how yet. I'll be cranking on it later this evening, but any thoughts/help would be appreciated. 🙏
j
How do you access the state in your components currently?
a
Copy code
props.location.state
I can usually get state variables out of that, but they are being lost in the router.
I'll be figuring that out later this evening
j
Hmm that is strange. Does a regular Route component work for you?
a
I can pass stuff through a regular route. The
state
is in the
...rest
, which is not passed down to
children
That's where the data is getting lost
OK, here's the solution:
Copy code
export default function UnauthenticatedRoute(props) {
  const { children, ...rest } = props;
  const { isAuthenticated } = useAppContext();
  const redirect = querystring("redirect");

  return (
    <Route {...rest}>
      {
        !isAuthenticated
        ? React.cloneElement(children, props)
        : <Redirect to={redirect === "" || redirect === null ? "/" : redirect} />
      }
    </Route>
  );
}
We don't de-structure it initially, and for the children we do
React.cloneElement(children, props)
, which is where the magic happens.
j
Ah I see, that makes sense. Thanks for tracking it down. If you can open a PR for this, I’ll update the guide with it.
t
If you don't want to clone, maybe you could make children a callback function that takes the props of the parent. i.e. a render prop.