Home > other >  How can I call scrollIntoView on an ref in React
How can I call scrollIntoView on an ref in React

Time:01-05

When I call someFun, I want to make formRef visible on the screen(it is on the top of the page, I may have scrolled to the bottom when I call someFun), is there standart way to do that?

function List(props) {

    const formRef = useRef(null);


    const someFun = params => {

        if (formRef && formRef.current) {
      

          //error FormRef.current.scrollIntoView is not a function
          formRef.current.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'start' });
        }
    }
}


This is the form component used in the above parent component: it is a ant design form component: the link is here https://3x.ant.design/components/form/#header

import { Form, Icon, Input, Button, Checkbox } from 'antd';

class NormalLoginForm extends React.Component {
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <Form.Item>
          {getFieldDecorator('username', {
            rules: [{ required: true, message: 'Please input your username!' }],
          })(
            <Input
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="Username"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: 'Please input your Password!' }],
          })(
            <Input
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="Password"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('remember', {
            valuePropName: 'checked',
            initialValue: true,
          })(<Checkbox>Remember me</Checkbox>)}
          <a className="login-form-forgot" href="">
            Forgot password
          </a>
          <Button type="primary" htmlType="submit" className="login-form-button">
            Log in
          </Button>
          Or <a href="">register now!</a>
        </Form.Item>
      </Form>
    );
  }
}

const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(NormalLoginForm);

ReactDOM.render(<WrappedNormalLoginForm />, mountNode);

CodePudding user response:

This how you can pass the ref from your NormalLoginForm to your List component.

In your List component you need to use forwardRef because it gives the child component a reference to a DOM element created by its parent component

Example

App

import "./styles.css";
import List from "./List";
import { useRef } from "react";

export default function App() {
  const targetElement = useRef();
  const scrollingTop = (event) => {
    const elmnt = targetElement;
    elmnt.current.scrollIntoView({
      behavior: "smooth",
      block: "center",
      inline: "start"
    });
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <p>lorem ipsum </p>
      <div style={{ height: "200vh", backgroundColor: "orange" }}>
        <h1>Example Form Tag </h1>
        <button id="btnAppear" onClick={scrollingTop}>
          Submit Scroll bottom
        </button>
      </div>
      <List ref={targetElement} />
    </div>
  );
}

List

import { forwardRef } from "react";
const List = (ref) => {
  return (
    <div
      style={{
        backgroundColor: "purple",
        paddingTop: "50px",
        color: "white"
      }}
      ref={ref}
    >
      <h1>List View</h1>
    </div>
  );
};

export default forwardRef(List);

DEMO

  •  Tags:  
  • Related