最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React ScrollIntoView() not working correctly? - Stack Overflow

programmeradmin4浏览0评论

At a bit of a crossroads here and I cant seen to figure out why. I have a login / registration page where I'm using ref.current?.scrollIntoView({ behavior: 'smooth' }); and it works pletely fine, but when I apply the same principle to a different page, it causes the page to reload and add a '?' to the end of the url. I'm not navigating anywhere though, and the console is reading 'No routes matched location ....' although I'm already on that page. Here is the page that works:

const SignIn = () => {

    const ref = useRef(null);
    const log = useRef(null);

    const [showLoader, setShowLoader] = useState(false);

    const { Login } = useContext(AuthContext);
    const { SignUp } = useContext(AuthContext);
    const { ForgotPassword } = useContext(AuthContext)

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [zipcode, setZipCode] = useState('');
    const [phoneNumber, setPhoneNumber] = useState('');
    const [role, setRole] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const handleClick = () => {
        ref.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const handleBackClick = () => {
        log.current?.scrollIntoView({ behavior: 'smooth' });
    };
...//
return (
        <div className='signInContainer'>
            <div className='signInPage'>
                <div ref={log} className='signinColContainer'>
                    <div className='loginContainer'>
                        <form className='loginFormContainer' onSubmit={handleLogin}>
                            <h2 className='logHeader'>Wele back!</h2>
                            <div className='regInputContainer'>
                                <input className='regInput' type="email" placeholder="Email" onChange={(a) => setEmail(a.target.value)} value={email} disabled={showLoader} />
                                <input className='regInput' type="password" placeholder="Password" onChange={(a) => setPassword(a.target.value)} value={password} disabled={showLoader} />
                            </div>
                            <h5 className='forgotPass' onClick={forgotHandler}>Forgot your password?</h5>
                            <h6 className='forgotPassHelper'>Enter your email and click 'Forgot your password?'</h6>
                            <LoadingButton
                                text="Log In"
                                syleName='regBtnStyle'
                                loading={showLoader}
                                disabled={
                                    email === '' ||
                                    password === '' ||
                                    showLoader
                                } />
                        </form>
                    </div>
                    <div className='regBtnContainer'>
                        <div className='regSidePage'>
                            <h2 className='regHeader'>New Here?</h2>
                            <h3 className='regP'>Joining Acquired easy, and takes under a minute! Plus, signing up with up will always be free</h3>
                            <button className="signUpRegBtn" onClick={handleClick}>Sign Up</button>
                        </div>
                    </div>
                </div>
                <div ref={ref} className='signUpColContainer'>
                    <div className='regBtnContainer'>
                        <div className='regSidePage'>
                            <h2 className='regSideHeader'>Remembered you have an account?</h2>
                            <h4 className='regP'>Log in and get your deals closed faster</h4>
                            <button className="signUpRegBtn" onClick={handleBackClick}>Log in</button>
                            <h5 className='orText'>- or -</h5>
..//

This one works perfectly fine every single time, but can someone tell me why this one doesn't? (css is the same for both):

const PostProperty = () => {

    const stepOne = useRef(null);
    const stepTwo = useRef(null);
    const stepThree = useRef(null);
    const stepFour = useRef(null);

    const navigate = useNavigate();

    const handleOneTwo = () => {
        stepTwo.current?.scrollIntoView({ block: "nearest", behavior: 'smooth' });
    };

    const handleTwoOne = () => {
        stepOne.current?.scrollIntoView({ block: "nearest", behavior: 'smooth' });
    };

    return (
        <div className="postPropContainer">
            <div className="postPropBox">
                <div ref={stepOne} className="stepOneContainer">
                    <div className='innerStepContainer'>
                        <form className="propertyAddress">
                            propertyAddress
                            <div>
                                <button onClick={handleOneTwo}>
                                    btn
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div ref={stepTwo} className="stepTwoContainer">
                    <div className='innerStepContainer'>
                        <form className="propertyNumbers">
                            <div>
                                propertyAddress
                                <button >
                                    btn
                                </button>
                                <button onClick={handleTwoOne}>
                                    backbtn
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div ref={stepThree} className="stepThreeContainer">
                    <div className='innerStepContainer'>
                        <form className="propertyDesc">
                            <div>
                                propertyAddress
                                <button >
                                    btn
                                </button>
                                <button >
                                    backbtn
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div ref={stepFour} className="stepFourContainer">
                    <div className='innerStepContainer'>
                        <div className="reviewContainer">
                            <div>
                                reviewContainer
                                <button >
                                    onSubmit
                                </button>
                                <button >
                                    backbtn
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
export default PostProperty;

At a bit of a crossroads here and I cant seen to figure out why. I have a login / registration page where I'm using ref.current?.scrollIntoView({ behavior: 'smooth' }); and it works pletely fine, but when I apply the same principle to a different page, it causes the page to reload and add a '?' to the end of the url. I'm not navigating anywhere though, and the console is reading 'No routes matched location ....' although I'm already on that page. Here is the page that works:

const SignIn = () => {

    const ref = useRef(null);
    const log = useRef(null);

    const [showLoader, setShowLoader] = useState(false);

    const { Login } = useContext(AuthContext);
    const { SignUp } = useContext(AuthContext);
    const { ForgotPassword } = useContext(AuthContext)

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [zipcode, setZipCode] = useState('');
    const [phoneNumber, setPhoneNumber] = useState('');
    const [role, setRole] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const handleClick = () => {
        ref.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const handleBackClick = () => {
        log.current?.scrollIntoView({ behavior: 'smooth' });
    };
...//
return (
        <div className='signInContainer'>
            <div className='signInPage'>
                <div ref={log} className='signinColContainer'>
                    <div className='loginContainer'>
                        <form className='loginFormContainer' onSubmit={handleLogin}>
                            <h2 className='logHeader'>Wele back!</h2>
                            <div className='regInputContainer'>
                                <input className='regInput' type="email" placeholder="Email" onChange={(a) => setEmail(a.target.value)} value={email} disabled={showLoader} />
                                <input className='regInput' type="password" placeholder="Password" onChange={(a) => setPassword(a.target.value)} value={password} disabled={showLoader} />
                            </div>
                            <h5 className='forgotPass' onClick={forgotHandler}>Forgot your password?</h5>
                            <h6 className='forgotPassHelper'>Enter your email and click 'Forgot your password?'</h6>
                            <LoadingButton
                                text="Log In"
                                syleName='regBtnStyle'
                                loading={showLoader}
                                disabled={
                                    email === '' ||
                                    password === '' ||
                                    showLoader
                                } />
                        </form>
                    </div>
                    <div className='regBtnContainer'>
                        <div className='regSidePage'>
                            <h2 className='regHeader'>New Here?</h2>
                            <h3 className='regP'>Joining Acquired easy, and takes under a minute! Plus, signing up with up will always be free</h3>
                            <button className="signUpRegBtn" onClick={handleClick}>Sign Up</button>
                        </div>
                    </div>
                </div>
                <div ref={ref} className='signUpColContainer'>
                    <div className='regBtnContainer'>
                        <div className='regSidePage'>
                            <h2 className='regSideHeader'>Remembered you have an account?</h2>
                            <h4 className='regP'>Log in and get your deals closed faster</h4>
                            <button className="signUpRegBtn" onClick={handleBackClick}>Log in</button>
                            <h5 className='orText'>- or -</h5>
..//

This one works perfectly fine every single time, but can someone tell me why this one doesn't? (css is the same for both):

const PostProperty = () => {

    const stepOne = useRef(null);
    const stepTwo = useRef(null);
    const stepThree = useRef(null);
    const stepFour = useRef(null);

    const navigate = useNavigate();

    const handleOneTwo = () => {
        stepTwo.current?.scrollIntoView({ block: "nearest", behavior: 'smooth' });
    };

    const handleTwoOne = () => {
        stepOne.current?.scrollIntoView({ block: "nearest", behavior: 'smooth' });
    };

    return (
        <div className="postPropContainer">
            <div className="postPropBox">
                <div ref={stepOne} className="stepOneContainer">
                    <div className='innerStepContainer'>
                        <form className="propertyAddress">
                            propertyAddress
                            <div>
                                <button onClick={handleOneTwo}>
                                    btn
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div ref={stepTwo} className="stepTwoContainer">
                    <div className='innerStepContainer'>
                        <form className="propertyNumbers">
                            <div>
                                propertyAddress
                                <button >
                                    btn
                                </button>
                                <button onClick={handleTwoOne}>
                                    backbtn
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div ref={stepThree} className="stepThreeContainer">
                    <div className='innerStepContainer'>
                        <form className="propertyDesc">
                            <div>
                                propertyAddress
                                <button >
                                    btn
                                </button>
                                <button >
                                    backbtn
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div ref={stepFour} className="stepFourContainer">
                    <div className='innerStepContainer'>
                        <div className="reviewContainer">
                            <div>
                                reviewContainer
                                <button >
                                    onSubmit
                                </button>
                                <button >
                                    backbtn
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
export default PostProperty;
Share Improve this question asked Dec 27, 2022 at 18:58 Christopher KoziolChristopher Koziol 2131 gold badge3 silver badges12 bronze badges 3
  • 1 Try adding vent.preventDefault and event.stopPropagation to your on click events. So we can ensure that an event is not bubbling up to the window. – Subramonian Inian Commented Dec 27, 2022 at 19:13
  • @SubramonianInian just tried and the preventDefault solved it. Thought I had tried that but that got it working. Thank you! – Christopher Koziol Commented Dec 27, 2022 at 23:27
  • Awesome, it's always good to handle the synthetic events :) – Subramonian Inian Commented Dec 28, 2022 at 6:08
Add a ment  | 

2 Answers 2

Reset to default 2

Updated the functions to include preventDefault and that fixed it. Functions are now:

const handleOneTwo = (e) => {
        e.preventDefault();
        stepTwo.current?.scrollIntoView({ block: "nearest", behavior: 'smooth' });
    };

Add event.preventDefault and event.stopPropagation to your on click events. So, we can ensure that an event is not bubbling up to the window.

发布评论

评论列表(0)

  1. 暂无评论