I know how to create a regular back button. But I want to create a button that takes you back one step in the URL and not to the previous page. In that way I can use the button on different places and dont have to change anything in the code. But I cant figure it out. I am a newbie.
example: if I am at stackoverflow.com and I navigate myself directly to a question like https://stackoverflow.com/questions/ask I want to be able to click the backbutton and end up in https://stackoverflow.com/questions So I can view other questions.
I am using TypeScript,React,Next languanges. So I can only use a script from those. I found a similar question here but they are using Angular and I dont know how to convert that to Next.js
I appreciate any help, clue whatever you can help me with.
CodePudding user response:
You can make ad hoc solution with simple string processing:
const BackButton = () => {
const { asPath } = useRouter();
const backUrl = asPath.slice(0, asPath.lastIndexOf('/'));
return <a href={backUrl}> Back </a>;
}
If you have basePath or locale then you can concatenate them to asPath.