Alpit Anand
Alpit Anand

Reputation: 1258

Why the ref in react is null here?

I have been experimenting with popmotion pure, since animation will have to use "ref" i am using it.
Here, why the value of ref(number) is null.

import React from 'react'
import {
  styler,
  tween,
  merge,
  action,
  easing
} from "popmotion";

class Demo extends React.Component {
  constructor(props) {
    super(props)
    this.count = React.createRef();
  }

  componentDidMount() {
    const number = this.count.current.querySelector('#count');
    const updateCounter = (v) => {
      console.log(v)
      return (number.innerHTML = v)
    }

    tween({
      from: 0,
      to: 300,
      flip: Infinity,
      duration: 4000
    }).start(updateCounter);
  }

  render() {

    return ( 
      <div>
        <p  ref={this.count} id='count'></p>
        <div id="ball"></div>
      </div>
    )
  }
}

export default Demo

It return error as TypeError: Cannot set property 'innerHTML' of null

However, if I use this document instead of null, it's working fine

 const number = document.querySelector('#count');

Can someone please guide me through. Thanks

Upvotes: 2

Views: 229

Answers (1)

Abdullah
Abdullah

Reputation: 2111

use

const number = this.count.current;

instead of

const number = this.count.current.querySelector('#count');

See live example

Upvotes: 1

Related Questions