'How to use React.useRef() in class component?

I need this code to be implemented in class component. It is in order to use a upload progress in my class component with react-toastify

function Example(){
  const toastId = React.useRef(null);
  function handleUpload(){
    axios.request({
      method: "post", 
      url: "/foobar", 
      data: myData, 
      onUploadProgress: p => {
        const progress = p.loaded / p.total;
        if(toastId.current === null){
            toastId = toast('Upload in Progress', {
            progress: progress
          });
        } else {
          toast.update(toastId.current, {
            progress: progress
          })
        }
      }
    }).then(data => {
      
      toast.done(toastId.current);
    })
  }
  return (
    <div>
      <button onClick={handleUpload}>Upload something</button>
    </div>
  )
}

How can i do that?



Solution 1:[1]

useRef() is among react hooks and hooks are meant to be used in Functional components but if you want to create a reference in a class-based component,

you can do it from the class constructor like the codes bellow:

  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

Check React.createRef().

Solution 2:[2]

Assign your value in constructor i.e bind with this.

createRef !== useRef, useRef is used to preserve the value across re-renders and for that in class component you need to bind it with this not createRef

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gargi Goyal