Skip to content

Instantly share code, notes, and snippets.

@pomber
Created October 16, 2023 14:31
Show Gist options
  • Save pomber/f22aa2a60727a56ac599831f6e14499e to your computer and use it in GitHub Desktop.
Save pomber/f22aa2a60727a56ac599831f6e14499e 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>
}
@pomber
Copy link
Author

pomber commented Oct 16, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment