import { useState, useEffect, useCallback } from 'react ' ;
export const useTextSelection () => {
const [, update] useState();
const forceUpdate = useCallback(() => update ({}), []);
const (selection, setSelection] useState (null);
const handleselection = () => {
setSelection (document.getSelection ()) ;
forceUpdate();
}
useEffect (() => {
setSelection(document.getSelection());
document.addEventListener('selectionchange', handleSelection);
return () => {
document.removeEventListener('selectionchange', handleSelection);
}, []}
return String(selection);
}
import { useTextSelection } from './hooks/useTextselection';
const App () => {
const selection = useTextSelection () ;
return (
<div className = "App">
<h1>Hello !</h1>
<h2>Select this text to see some magic!</h2>
<h3>{selection} </h3>
</div>
);
export default App;