-
-
Save langf00rd/ef545f91ed0c4975a02d9aa59ae82e41 to your computer and use it in GitHub Desktop.
Highlight selected text in code
This file contains hidden or 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
| function Code() { | |
| const ref = React.useRef() | |
| React.useEffect(() => { | |
| const handler = e => { | |
| const selected = document.getSelection().toString().trim() | |
| ref.current.querySelectorAll("span:not(:has(*))").forEach(element => { | |
| if (element.textContent === selected) { | |
| element.classList.add("selected") | |
| } else { | |
| element.classList.remove("selected") | |
| } | |
| }) | |
| } | |
| document.addEventListener("selectionchange", handler) | |
| return () => { | |
| document.removeEventListener("selectionchange", handler) | |
| } | |
| }, []) | |
| return <pre ref={ref}>...</pre> | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment