Created
October 16, 2023 14:31
-
-
Save pomber/f22aa2a60727a56ac599831f6e14499e to your computer and use it in GitHub Desktop.
Highlight selected text in code
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
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
See https://twitter.com/pomber/status/1713872576286753123