Created
October 16, 2023 14:11
-
-
Save pomber/27eb583b004ba2d94d56342302710de5 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