Last active
February 4, 2023 01:28
-
-
Save killshot13/197032167dd9e915e788ca059f2936d5 to your computer and use it in GitHub Desktop.
React useRef && forwardRef
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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