Learning React: how to useRef in custom component?

1.1k Views Asked by At

I'm learning React and I don't think I understand the concept of useRef properly. Basically, I want to include some tags in tagify input field when a user clicks on a chip that is rendered outside the input box.

My idea is to do something like this (App.js):

import Chip from '@material-ui/core/Chip';
import Tagify from "./Tagify"

...

class App extends React.Component {

...

   const { error, isLoaded, quote, tags } = this.state; //tags comes from the server

   var tagify = <Tagify tags={tags} />
   const addTagOnChipClick = (tag) => {
       tagify.addTag(tag)
     };

   const chips = tags.map(tag => (
       <span key={tag.name} className="chips">
         <Chip
           label={tag.name}
           variant="outlined"
           onClick={addTagOnChipClick(tag)}
           clickable
         />
       </span>
     ))

...

}

The tagify documentation says that

To gain full access to Tagify's (instance) inner methods, A custom ref can be used: <Tags tagifyRef={tagifyRef} ... />

My attempt to gain access to these inner methods was to use useRef (Tagify.js):

import Tags from '@yaireo/tagify/dist/react.tagify'

import '@yaireo/tagify/dist/tagify.css'

export default function Tagify(tags) {
   const tagifyRef = useRef()

   return (
       <Tags
           tagifyRef={tagifyRef}
           placeholder='Filter by tags...'
           whitelist={tags.tags}
       />
    )
}

However, tagifyRef.current is undefined. What I'm doing wrong? There's another way to access the inner methods?

Thank you very much!

1

There are 1 best solutions below

1
On

When are you accessing the ref? Make sure you access the ref only after the component has mounted i.e. in a useEffect:

import Tags from '@yaireo/tagify/dist/react.tagify'

import '@yaireo/tagify/dist/tagify.css'

export default function Tagify(tags) {
   const tagifyRef = useRef()

  React.useEffect(() => {
     console.log(tagifyRef.current)
  }, [])

   return (
       <Tags
           tagifyRef={tagifyRef}
           placeholder='Filter by tags...'
           whitelist={tags.tags}
       />
    )
}