Skip to content Skip to sidebar Skip to footer

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: &

Solution 1:

On custom components, ref needs to be forwarded.

An example would be like:

// inside Sales.jsconst 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.

Post a Comment for "Useref() Hook On A Custom Component"