Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useRef() Hook on a custom component

I'm trying do create a Navigation Bar that when the user click 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 declares as folowing, 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 folowing:

  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?

disclaimer: Sorry for bad english, i'm not a native speaker.

like image 741
yuridamata Avatar asked Apr 13 '20 16:04

yuridamata


People also ask

Can I use useRef in functional component?

The useRef is a hook that allows to directly create a reference to the DOM element in the functional component. Syntax: const refContainer = useRef(initialValue); The useRef returns a mutable ref object.

How do I use useRef Hooks?

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

Can we use ref on React component?

In order to get a reference to a React component, you can either use this to get the current React component, or you can use a ref to get a reference to a component you own. They work like this: var MyComponent = React.

Can you use a hook in a class component?

You can't use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component.


1 Answers

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.

like image 69
Jackyef Avatar answered Oct 23 '22 05:10

Jackyef