Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

useRef is not working with custom compnents

On custom components, ref needs to be forwarded.

An example would be like:
// inside index.js
return(
<Navbar scrollFunc={scrollToRef} />      
    <Mainlogo ref={mainLogoRef} />
    <Sales  ref={salesRef} />
    <Introduction ref={introductionRef} />
    <Blog ref={blogRef} />
<Footer />
)
// 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 render multiple DOM elements, so you need to be explicit about
where the `ref` should be assigned to.
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #useRef #working #custom #compnents
ADD COMMENT
Topic
Name
4+2 =