Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/juliankrispel/use-text-selection
React hook for tracking text selection
https://github.com/juliankrispel/use-text-selection
draft-js editor hooks react slatejs text-editor ui wysiwyg-editor
Last synced: 3 days ago
JSON representation
React hook for tracking text selection
- Host: GitHub
- URL: https://github.com/juliankrispel/use-text-selection
- Owner: juliankrispel
- License: mit
- Created: 2021-01-31T11:44:43.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2023-10-04T06:03:47.000Z (over 1 year ago)
- Last Synced: 2024-12-27T14:07:37.859Z (14 days ago)
- Topics: draft-js, editor, hooks, react, slatejs, text-editor, ui, wysiwyg-editor
- Language: TypeScript
- Homepage: https://juliankrispel.github.io/use-text-selection/
- Size: 717 KB
- Stars: 37
- Watchers: 2
- Forks: 6
- Open Issues: 3
-
Metadata Files:
- Readme: readme.md
- Changelog: CHANGELOG.md
- License: LICENSE.md
Awesome Lists containing this project
README
# use-text-selection
[React hook](https://reactjs.org/docs/hooks-reference.html) for tracking the state of the current text selection.
Useful when building any kind of UI that is displayed in relation to your text-selection. For example:
- Floating toolbars for richt text editing or content sharing.
- Autocomplete/suggestion featues in editors.## Basic usage
```tsx
import { useRef } from 'react'
import { useTextSelection } from 'use-text-selection'export const AutoComplete = () => {
const { clientRect, isCollapsed } = useTextSelection()
// to constrain text selection events to an element
// just add the element as a an argument like `useTextSelection(myElement)`if (clientRect == null) return null
return (
Autocomplete
);
}}
```### Constraining text selection events to an element
`useTextSelection` takes one argument called, which would be a dom element which constrains updates to inside the dom element.
Retrieve a reference to this dom element with the `querySelector` api or with React refs (recommended).
Here's an example:
```tsx
const MyTextSelectionComponent = () => {
const [ref, setRef] = useRef()
const { clientRect, isCollapsed } = useTextSelection(ref.current)if (clientRect == null) return null
return (
<>
setRef(el)}>
Autocomplete
>
);
}
```## Work with me?
I build editors for companies, or help their teams do so. Hit me up on [my website](http://jkrsp.com) to get in touch about a project.