yuridamata
yuridamata

Reputation: 519

useRef() Hook on a custom component

I'm trying do create a Navigation Bar that when the user clicks on one of the links, the page scrolls to some section. In the code above, each element is a section of my page:

    <Navbar scrollFunc={scrollToRef} />      
    <Mainlogo ref={mainLogoRef} />
    <Sales  ref={salesRef} />
    <Introduction ref={introductionRef} />
    <Blog ref={blogRef} />
    <Footer />

The 'refs' was declared as following, using the useRef hook:

  const mainLogoRef = useRef(null)
  const salesRef = useRef(null)
  const introductionRef = useRef(null)
  const blogRef = useRef(null)

The function I'm using to scroll is the following:

  const scrollToRef = ref => {
    window.scrollTo({ top: ref.current.offsetTop, behavior: "smooth" })
  }

The thing is that the 'current' key is always undefined. When I do something like that:

<div ref={salesRef}> <Sales  /><div>

or

<section ref={salesRef}> <Sales  /><section>

Things works just fine. I'm assuming that 'ref' works only on html 'pure' tags. Is there any way to use useRef hook in a custom component?

Upvotes: 29

Views: 41488

Answers (1)

Jackyef
Jackyef

Reputation: 5012

On custom components, ref needs to be forwarded.

An example would be like:

// inside Sales.js
const Sales = (props, ref) => (
  <div ref={ref}> // assigns the ref to an actual DOM element, the div
    /* anything you want to render here */
  </div>
)

export default React.forwardRef(Sales);

This is because ref is (usually) a reference to a DOM element. A React Component can renders multiple DOM element, so you need to be explicit about where the ref should be assigned to.

Upvotes: 44

Related Questions