Why behavior is different?

94
January 10, 2020, at 2:50 PM

What's the difference between createRef and ref={(c) => this.el = c}?

When I output each ref has same element but it not false.

why?

import React from "react"
class Home extends React.Component {
constructor(){
  super();
  this.el1 = React.createRef();
}
componentDidmount(){
  console.log(el1 === el2) // false   why false?
}
render(){
  return (
    <>
      <div ref={this.el1}>
        <span>A</span>
      </div>
      <div ref={(c)=> { this.el2 = c }}}>
        <span>A</span>
      </div>
    </>
  )
}
Answer 1

In the code both ref are pointing to two different DOMnodes that's why these are not same.

createRef is returning either a DOM node or a mounted instance of a component, depending on where you call it. Either way, what you have in hand is indeed straightforward as you've noted. But what if you want to do something with that reference? What if you want to do it when the component mounts?

Ref callbacks are great for that because they are invoked before componentDidMount and componentDidUpdate. This is how you get more fine-grained control over the ref. You are now not just grabbing DOM elements imperatively, but instead dynamically updating the DOM in the React lifecycle, but with fine-grained access to your DOM via the ref API.

READ ALSO
Are there any creative workarounds to get the browser to play audio on an inactive mobile device?

Are there any creative workarounds to get the browser to play audio on an inactive mobile device?

I built a gamified Pomodoro/Todo web app on React, and realized near the finishing stages of production that the audio won't fire if the phone isn't active (I know, rookie mistake)I searched here and confirmed what I feared to be true

81
Remove Duplicate Numbers in 2D Array Javascript [duplicate]

Remove Duplicate Numbers in 2D Array Javascript [duplicate]

I have a 2D array of number arrays like say

88
WebGL: How can you draw a pentagon?

WebGL: How can you draw a pentagon?

I am practicing WebGL and attempting to draw a pentagon, but I am not sure how to approach thisAny help would be much appreciated

139