3

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.

Jacin
  • 71
  • 9
  • Is the functional component related to the class component? Ie grandparent/parent/child? – rrd Jun 19 '20 at 08:57
  • Why don't you just convert your functional component into a class component, hence, it resembles the behavior described in the documentation. – Rostyslav Jun 19 '20 at 09:02

2 Answers2

4

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} />
   )
}
Majid Savalanpour
  • 1,642
  • 2
  • 16
  • 26
2

I don't work with useRef that often but I think it should look like this:

import React from 'react';
import { FilePond } from "react-filepond";

const Example = () => {
   const filePondRef = useRef(null);
   // you should be able to use filePondRef (filePondRef.current) instead of "this.pond"

   return(
      <FilePond ref={filePondRef} />
   )
}

Source: https://reactjs.org/docs/hooks-reference.html#useref

Tim Gerhard
  • 3,477
  • 2
  • 19
  • 40
  • ¡Thank you so much, it works! I forgot to include .current. Thank you Tim for solving my problem so fast! – Jacin Jun 19 '20 at 09:16