简体   繁体   中英

Scroll to the bottom of a scrollable div in react

I've tried numerous solutions to try scroll to the bottom of a div as at the bottom user feedback can be found on whether their registration form successfully submitted.

var objDiv = document.getElementById("form");
objDiv.scrollTop = objDiv.scrollHeight;

and

window.scrollTo(0,document.body.scrollHeight);

and

window.scrollTo(0,document.querySelector("#form").scrollHeight);

With no success

Here's the react code for the form

return (
    <div
      className={styles.register_container}
      id="register-container"
      style={{
        height: "100%",
        overflow: "scroll",
      }}
    >
      <HomeIcon />
      <div className={styles.login_button_container}>
        <p>Already have an account? </p>
        <button
          onClick={() => {
            router.push("/login");
          }}
        >
          Log in
        </button>
      </div>
      <div
        style={{
          padding: "60px 0",
          height: "100%",
          maxWidth: "300px",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
        id="form"
      >
        <img
          src="/assets/Logo/ROA_logowhite.png"
          style={{
            height: "100px",
            maxWidth: "100px",
          }}
          onClick={() => {
            var objDiv = document.getElementById("form");
            objDiv.scrollTop = objDiv.scrollHeight;
          }}
        />
        {page === 2 && (
          <div style={{ width: "100%" }}>
            <button className="back-button" onClick={backButtonHandler}>
              <FontAwesomeIcon icon={faAngleLeft} />
              Back
            </button>
          </div>
        )}
        {page === 1 && loginDetails}
        {page === 2 && personalDetails}

        <div style={{ width: "100%", padding: "5px 0" }}>
          <button
            className="form-button"
            onClick={buttonHandler}
            style={{ minHeight: "50px" }}
          >
            {submitButton}
          </button>
        </div>
        {loading && (
          <div
            style={{
              padding: "5px",
              width: "100%",
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <ReactLoading
              type="spin"
              color="#1dd760"
              height={50}
              width={50}
              id="loader"
            />
          </div>
        )}

        {registrationError && (
          <p className="form-submit-error">
            Registration error, refresh your page and try again
          </p>
        )}
        {true && (
          <div>
            <p
              style={{ marginBottom: "10px" }}
              className="form-submit"
              id="submit"
            >
              Redirecting to login ... You should receive a welcome email, if
              not please try registering again or visit the{" "}
              <a href="/contact" style={{ color: "#1dd760" }}>
                contact
              </a>{" "}
              page.
            </p>
          </div>
        )}
      </div>
    </div>
  );

I can't directly focus on the submit success message as setState is asynchronous in react. Just need a function that allows me to scroll the bottom of the div when the next/submit button is clicked

在此处输入图像描述

在此处输入图像描述

The proper way to access/modify DOM elements in React function components is to use the useRef hook. https://reactjs.org/docs/hooks-reference.html#useref

Here is an example how you can solve your problem:

import * as React from "react";

const Component: React.FunctionComponent = () => {
  const ref = React.useRef<HTMLDivElement>(null);
  const [success, updateSuccess] = React.useState(false);

  const buttonHandler = () => {
    updateSuccess(true);
    if (ref.current) {
      const offsetBottom = ref.current.offsetTop + ref.current.offsetHeight;
      window.scrollTo({ top: offsetBottom });
    }
  };

  return (
    <div>
    ...
      <button onClick={buttonHandler}>Scroll</button>
      {success ? (
        <div
          ref={ref}
          style={{ height: "2000px", display: !success && "none" }}
        >
          Long Success Message
        </div>
      ) : null}
    </div>
  );
};

export default Component;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM