I'm trying to access a class component method inside a function component. I have been reading for hours but I'm missing something.
To be precise, I'm trying to access a method (addFiles) of the Filepond component (https://pqina.nl/filepond/docs/patterns/frameworks/react/)
As readed in the documentation, I can ref the class component:
<FilePond ref={ref => this.pond = ref}/>
And then I can use the method like this:
this.pond.addFiles();
But I can't use that method in my Function because 'this' can't be used in a Function.
TypeError: Cannot set property 'pond' of undefined
I though useRef hook could help, but it only works in html elements.
import React from 'react';
import { FilePond } from "react-filepond";
const Example = () => {
//How can I use this.pond.addFiles() here?
return(
<FilePond ref={ref => this.pond = ref} />
)
}
Thank you for your help.
UseRef will create a ref. The useRef Hook is a function that returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
const refContainer = useRef(initialValue);
You can use this code
import React, { useRef } from 'react';
import { FilePond } from "react-filepond";
const Example = () => {
const file = useRef(null);
// Use file.current.addFiles() instead of this.pond.addFiles();
return(
<FilePond ref={file} />
)
}