magikarp
magikarp

Reputation: 470

React, JS - functionality difference in different ways of using refs

What is the difference between the following? Particularly in terms of functionality?

<div ref={this.myRef}/>
<div ref={(elem) => {this.myRef = elem;}}/> 

When I do the second of the above and call this.myRef.scrollIntoView({behavior: 'smooth'}), the scrolling behavior works. However, after changing it to the first, it doesn't work.

Upvotes: 0

Views: 50

Answers (4)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

The ref prop provides you the element instance to set as React reference. When you do

<div ref={this.myRef} />

nothing is set as the reference so the variable this.myRef don't know which element to store.

Otherwise

<div ref={(elem) => {this.myRef = elem;}}/> 

This code provides you the element to store as reference by it's elem param. Now the this.myRef knows which element to store as reference.

Upvotes: 0

Rakib Uddin
Rakib Uddin

Reputation: 876

The are same basically. But with the 2nd method you get more control. You can pass more parameters with the 2nd method.

import React, { Component } from "react";

class App extends Component {
constructor(props) {
super(props);
this.setTextInputRef = (element, name) => {
  this.textInput = element;
  this.x = name;
};
}
componentDidMount = () => {
if (this.textInput) {
  this.textInput.focus();
  console.log(this.x);
}
};

render() {
return (
  <div>
    <input
      placeholder="Input"
      ref={e => this.setTextInputRef(e, "hello")}
    />
  </div>
);
}
}

export default App;

Run this example. Home this helps

Upvotes: 0

Konstantin Modin
Konstantin Modin

Reputation: 1333

in first case you have link to the div in this.myRef.current when it mounts to DOM.

in second case you pass function as ref. This function will receive as first argument your node (div). And you can manipulate it in this function

<div ref={node => {
    console.log(node);
    // do something useful with node
}}/> 

Upvotes: 1

Matjuhh
Matjuhh

Reputation: 61

It's difficult to say without context, but probably this.myRef is not set in the first case. If you want to use the first option, you need to manually set it (by using something like React.createRef()), see the react docs on this.

Upvotes: 0

Related Questions