Listen to back button in mobile browser and e.preventDefault() then use our separate function in react function
I am working on a react web app add want to preventDefault back button to my function in react function
for exact code use check -https://github.com/rishabhjainfinal/react-expence-calculator/blob/main/src/App.js
yes I can use react routing but I wanna test this way first
function App() {
function onBack(){
if (CP === "Month"){
UpdateCP("Year")
}
else if (CP === "Day"){
UpdateCP("Month")
}
}
//some event listener function to prevent to go back
switch (CP){
case 'Day':
return (<Day date={AD} CP={CP} UpdateCP={UpdateCP}/>)
case 'Year':
return (<Year monthNames={monthNames} CP={CP} UpdateCP={UpdateCP} UpdateAM={UpdateAM} Save_in_excel={Save_in_excel}/>)
default :
return (<Month month={AM} CP={CP} UpdateCP={UpdateCP} UpdateAD={UpdateAD} AM={AM} AY={AY} monthNames={monthNames} />)
}
}
This is my first react app and want to do it this way only.
Yes, there are many different ways but none of then is working:
- 'https://ift.tt/3b0pNnI'
- 'https://ift.tt/2KP0tGC'
- 'https://ift.tt/38OKIYa'
the more detailed description -> supposed you created a react P.W.App of single-page but you wanna change the components every time back button is pressed like mobile back button or browser back button, and this is only possible by listening to the press of the back-button and prevent default case and run my own function this takes 2 steps:-
- listen to the event
- run function
try using
const [finishStatus, setfinishStatus] = useState(false);
useEffect(() => {
const onBackButtonEvent = (e) => {
console.log('kdfjlsdjfds')
e.preventDefault();
if (!finishStatus) {
if (window.confirm("Do you want to go back ?")) {
setfinishStatus(true)
// your logic
// props.history.push("/");
} else {
window.history.pushState(null, null, window.location.pathname);
setfinishStatus(false)
}
}
}
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', onBackButtonEvent);
return () => {
window.removeEventListener('popstate', onBackButtonEvent);
};
});
this code does nothing in my app (no effect at all) for of componentDidMount and componentDidUnMount in useEffect hook, our whole page is a single component when it Unmounts page unloads 😥
from Recent Questions - Stack Overflow https://ift.tt/3pArNY8
https://ift.tt/eA8V8J
Comments
Post a Comment