Skip to content

Instantly share code, notes, and snippets.

@killshot13
Last active February 4, 2023 01:28
Show Gist options
  • Save killshot13/197032167dd9e915e788ca059f2936d5 to your computer and use it in GitHub Desktop.
Save killshot13/197032167dd9e915e788ca059f2936d5 to your computer and use it in GitHub Desktop.
React useRef && forwardRef
// sample use case: scroll to a React component by using a reference.
import React, { forwardRef, useRef } from 'react'
// @ts-ignore
const Article = forwardRef(function Article({ onClick }, ref) {
return (
<article ref={ref}>
<h1>A React article for Latin readers</h1>
// Rest of the article's content...
<button onClick={onClick}>Back to the top</button>
</article>
)
})
// ...
const AnotherComponent = () => {
const articleRef = useRef()
const handleBackClick = () =>
articleRef.current.scrollIntoView({ behavior: 'smooth' })
return <Article ref={articleRef} onClick={handleBackClick} />
}
export default AnotherComponent
// sample use case: scroll to an element by using a reference.
import React, { useRef } from 'react'
const Article = () => {
const titleRef = useRef()
function handleBackClick() {
titleRef.current.scrollIntoView({ behavior: 'smooth' })
}
return (
<article>
<h1 ref={titleRef}>A React article for Latin readers</h1>
// Rest of the article's content...
<button onClick={handleBackClick}>Back to the top</button>
</article>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment