Reactjs Scroll with multiple ref

I have a doubt with the ref in reactjs. Sorry, it is dumb but I’m still learning. Well, the issues are I’m trying to scroll to react using ref but my question is because I want to use multiple references.

My code is this:

import React, { Component } from "react";
import './App.css';
import { Row, Col,Image,ListGroup,Button,Jumbotron,Container} from 'react-bootstrap';



class App extends Component {

  constructor(props) {
    super(props)
    this.myRef = React.createRef()
    this.myRef2 = React.createRef()    // Create a ref object 
}


handleOnClick = (event) => {
  //.current is verification that your element has rendered

  window.scrollTo(2, this.myRef2.current.offsetTop) 
}


  render() {


    return (
    <div className="App">
             <button onClick={this.handleOnClick}>Click me</button>

      <Row>
        <Col className="menu text-center" lg ={4}>

          <div className="picture" >
            <Image src={process.env.PUBLIC_URL + '/Images/picture.jpg'} roundedCircle />
          </div>

          <h1 className="menu-name">Carlos Deseda</h1>

          <h4 className="menu-office">Software Engineer - Web Developer</h4>

          <div>
          <Row>
              <Col lg= {3}></Col>
              <Col lg= {6} className="menu-text">
                <ListGroup >
                  <ListGroup.Item>ABOUT</ListGroup.Item>
                  <ListGroup.Item>WORK EXPERIENCE</ListGroup.Item>
                  <ListGroup.Item>EDUCATION</ListGroup.Item>
                  <ListGroup.Item>SKILLS </ListGroup.Item>
                  <ListGroup.Item>CONTACT</ListGroup.Item>
                </ListGroup>
              </Col>
              <Col lg= {3}></Col>
            </Row>
          </div>

        </Col>

        <Col className="info text-center" lg ={8}>

  <div className="ref1" ref={this.myRef}> FirtsOne </div>
  <div className="ref2" ref={this.myRef2}>SecondOne</div>



        </Col>

      </Row>

    </div>

  )}
}

export default App;

With this

this.myRef = React.createRef()

this.myRef2 = React.createRef()

I can change the value of my div and works but I want to know if I can join this two in only one react.createRef() like array or I dont know. Thanks for any help!!

Answer

Instead of creating ref like,

this.myRef = React.createRef()

You can just define an empty array in your constructor,

constructor(props) {
    super(props)
    this.myRef = [];
}

Now you can use callback ref pattern to create ref,

<div className="ref1" ref={(ref) => { this.myRef[0] = ref }}> FirtsOne </div>
<div className="ref2" ref={(ref) => { this.myRef[1] = ref }}>SecondOne</div>

To scroll you can use scrollIntoView,

handleOnClick = (event) => {
  //.current is verification that your element has rendered
  console.log(this.myRef[1]);
  this.myRef[1].scrollIntoView(); 
}

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *