Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

javascript - React Router Dom v4 handle browser back button

How do I disable a browser back button click from user using react-router-dom v4?

I am showing a modal on a page and when the user presses browser back button then the user is taken to the previous screen, instead I want to simply close the modal.

I tried doing this

onBackButtonEvent(event) {
    event.preventDefault();  
    // the user shouldn't be able to move backward or forward  
}
componentDidMount() {
    window.onpopstate = this.onBackButtonEvent;
}

But this doesn't prevent the user from going backward or forward. Is there a way to handle this via react-router-dom?

I have tried multiple solutions but nothing seems to work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know this question's a little old but I stumbled on it while looking for the answer myself. There's no clean way to "disable" the back button but to enable the user to only close the modal when clicking the browser back button I found this to work.

Simply pass the history to your modal component in props and call the below on the componentWillUnmount function.

componentWillUnmount() {
    this.props.history.goForward();
}

This will seamlessly force the browser to stay on the same page but close the modal (assuming it's a class component).

UPDATE: If using functional components, the above componentWillUnmount function looks like the hook below.

React.useEffect(() => {
    return () => {
            props.history.goForward();
        }
    }, []);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...