1

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!

2
  • Possibly their docs are wrong? Try using <Tags ref={tagifyRef} … ? Commented Oct 18, 2020 at 18:33
  • @MishaReyzlin I don't think so. with ref I got the following error: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Commented Oct 18, 2020 at 18:48

1 Answer 1

2

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}
       />
    )
}

Sign up to request clarification or add additional context in comments.

1 Comment

But there's anyway I can access the ref from the tagify variable (var tagify = <Tagify tags={tags} />) in the App.js file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.