画面上で選択中の文字列を取得するにはSelection APIを使用します。
import { useCallback, useEffect } from 'react'
export function Sample() {
const handleSelectionChange = useCallback(() => {
const selection = document.getSelection()
console.log(selection?.toStoring()) // 選択されている文字列をコンソールに出力
}, [])
useEffect(() => {
document.addEventListener('selectionchange', handleSelectionChange)
return () => {
document.removeEventListener('selectionchange', handleSelectionChange)
}
}, [handleSelectionChange])
return (
<p>
サンプルのテキスト。サンプルのテキスト。サンプルのテキスト。サンプルのテキスト。サンプルのテキスト。
</p>
)
}