1

I am in my react app and I want to go from https://example.com/route1 to https://example.com/route1/route1.1 using history.push.

I remember that using history.push(.) allows me to go back one route, but what is the cleanest way of going from /route1 to /route1/route1.1 using history.push?

edit: this is a simplified route example, in my application there can be more subroutes

tilly
  • 2,229
  • 9
  • 34
  • 64
  • https://stackoverflow.com/questions/63471931/using-history-with-react-router-dom-v6 maybe this could help you – A.Vinuela Feb 15 '22 at 09:36
  • So.... `history.push("/route1/route1.1")`? What have you tried? What isn't working as you expect? Is there an issue navigating? Can you add your code to the question? https://stackoverflow.com/help/minimal-reproducible-example Does the RRDv5 [nesting demo](https://v5.reactrouter.com/web/example/nesting) help clear it up for you? – Drew Reese Feb 15 '22 at 09:38
  • Like I put in the edit, the routes aren't always this simple, sometimes there are more than 4 levels of subroutes – tilly Feb 15 '22 at 09:39

2 Answers2

1

The latest documentations suggest that you should use useNavigate hook or the <Navigate /> component for navigating.

Reference: https://reactrouter.com/docs/en/v6/api#navigation

If you are using react-router v5, and you want to navigate to a relative path, then you need to construct the new path by getting the current path via useLocation. Here's the location object spec: https://v5.reactrouter.com/web/api/location

const location = useLocation()
const history = useHistory()

const navigate = () => history.push(`${location.pathname}${NEW_PATH_RELATIVE_TO_CURRENT_LOCATION}`)

You can also do a replace instead of push by using history.replace instead of history.push.

Checkout https://v5.reactrouter.com/web/api/history for complete list of operations available over history object.

Akshay Kumar
  • 875
  • 13
  • 29
0

Adding this as a possible answer, but still open for a more direct way of doing it with just history:

I used the useRouteMatch hook to get the present URL and then added the new route to that url.

import { Box, Typography, Button } from '@mui/material';
import { useHistory, useRouteMatch } from 'react-router';

export const ProposalListItem = ({
  proposal: {
    name,
    proposed_asset: { type },
    notes,
  },
}) => {
    const history = useHistory();
    const { url } = useRouteMatch();

  return (
    <Box border='1px solid black' p={2} mt={3} display='flex'>
      <Box>
          <Button onClick={() => history.push(`${url}/test`)} variant='outlined'>More info</Button>
      </Box>
    </Box>
  );
};
tilly
  • 2,229
  • 9
  • 34
  • 64