0

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.

4
  • What does the rest of the component look like? Are you using createRef in the first case? Commented Mar 14, 2020 at 9:26
  • It would be helpful if you could edit your question to provide complete examples for both cases, including the constructor, render method and usage. Commented Mar 14, 2020 at 9:36
  • @TomFenech, I'm using createRef in both cases. Commented Mar 14, 2020 at 9:36
  • If you want a definitive answer, you need to add a complete example to your question. Commented Mar 14, 2020 at 11:56

4 Answers 4

1

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
}}/> 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

I'm already manually setting it with React.createRef() in both cases.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.