Skip to content

Instantly share code, notes, and snippets.

@pomber
Created October 16, 2023 14:11
Show Gist options
  • Save pomber/27eb583b004ba2d94d56342302710de5 to your computer and use it in GitHub Desktop.
Save pomber/27eb583b004ba2d94d56342302710de5 to your computer and use it in GitHub Desktop.
Highlight selected text in code
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