I'm using NextJS (v.13.4.15) app directory
I'm using a react-native webview to display a website inside of a mobile app, so a back button is critical for navigation (I cannot access the browser's back button)
I want something like
'use client' for client component:
<button
onClick={() => window.history.state && window.history.state.idx > 0 ? router.back() : router.push('/')}
>
However I cannot get this to work, NextJS seems to have issues with accessing window.history (or maybe it's not NextJS and it's just a privacy thing)
And even if I can access the window, the window object contains confusing and inconsistent children properties and values like this:
{
"__NA": true,
"tree": [
"",
{
"children": [
"courses",
{
"children": [
[
"slug",
"hacking-success",
"c"
],
{
"children": [
"__PAGE__",
{}
]
}
]
}
]
},
null,
null,
true
]
}
There has to be a way to check if (router.back()) is null or cannot go back, and then router.push('/) right?
ideally:
router.back() ?? router.push('/')
or can someone help explain this history.state.idx.tree? The length doesn't seem to match the number of history items from navigation, but rather the parent/hierarchy of the URL
I've wished that NextJS would have a method on the router that would return the history or provide a null/false value if the history is empty
However I've read the useRouter() documentation and no method seems to exist
I've tried to access the window.history
object but cannot write code to check if history does not contain a path to navigate back to
My only other idea is to pass a parameter when linking to a "non home page" that can be checked and then conditionally change the back button logic based on the parameter, but that seems inefficient
This answer is close but also seems inefficient