Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 213
MUHAMMED IQBAL Avatar asked Jun 21 '20 13:06

MUHAMMED IQBAL


People also ask

Can you use useRef in class component?

useRef is the hook to create refs in functional components, but you can also use refs in your class components! The way you do it is by using the createRef function.

Can I use useRef in functional component?

The useRef is a hook that allows to directly create a reference to the DOM element in the functional component. Syntax: const refContainer = useRef(initialValue); The useRef returns a mutable ref object.

Can we use useRef in React?

Accessing DOM Elements In general, we want to let React handle all DOM manipulation. But there are some instances where useRef can be used without causing issues. In React, we can add a ref attribute to an element to access it directly in the DOM.


1 Answers

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().

like image 143
Mwibutsa Floribert Avatar answered Nov 03 '22 11:11

Mwibutsa Floribert