How to use React.useRef() in class component?
Asked Answered
W

3

46

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?

Weatherby answered 21/6, 2020 at 13:16 Comment(0)
H
98

useRef() is among react hooks which 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 code below:

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

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

Check React.createRef().

Haircut answered 21/6, 2020 at 13:21 Comment(0)
S
7

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

Schulein answered 11/3, 2022 at 15:29 Comment(2)
you should add a code exampleSimplehearted
As @FacundoColombier said, the answer should contain a code example.Tillio
E
0

How to use React.useRef() in class extends component:

import { Component, createRef } from "react";

export default class App extends Component{
 constructor(props){
    super(props);
   
    this.myP = createRef();
    window.addEventListener("load", ()=>this.prompt());
 }
 prompt(){
     this.myP.current.innerText = 'Hello World!'
 }
 render(){
    return(
        <>
          <p ref={this.myP} />        
        </>
    );
 }
}
Egocentric answered 11/6, 2023 at 0:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.