Skip to content

Commit b03c7b5

Browse files
committed
Add selectionStart / selectionEnd getter to handle
1 parent ab1c455 commit b03c7b5

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/textarea.tsx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ export type CaretPosition = {
121121

122122
export type RichTextareaHandle = {
123123
textareaRef: React.RefObject<HTMLTextAreaElement>;
124+
selectionStart: number;
125+
selectionEnd: number;
124126
setRangeText: (
125127
text: string,
126128
start: number,
@@ -168,6 +170,12 @@ export const RichTextarea = forwardRef<RichTextareaHandle, RichTextareaProps>(
168170
propRef,
169171
() => ({
170172
textareaRef: ref,
173+
get selectionStart() {
174+
return ref.current?.selectionStart ?? 0;
175+
},
176+
get selectionEnd() {
177+
return ref.current?.selectionEnd ?? 0;
178+
},
171179
setRangeText: (text, start, end, preserve) => {
172180
if (!ref.current) return;
173181
setRangeText(ref.current, text, start, end, preserve);

stories/toolbar.stories.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ export const Toolbar = () => {
1717
<div>
1818
<button
1919
onClick={() => {
20-
const start = ref.current.textareaRef.current.selectionStart;
21-
const end = ref.current.textareaRef.current.selectionEnd;
20+
const start = ref.current.selectionStart;
21+
const end = ref.current.selectionEnd;
2222
ref.current.setRangeText(
2323
`**${text.slice(start, end)}**`,
2424
start,
@@ -30,17 +30,17 @@ export const Toolbar = () => {
3030
</button>
3131
<button
3232
onClick={() => {
33-
const start = ref.current.textareaRef.current.selectionStart;
34-
const end = ref.current.textareaRef.current.selectionEnd;
33+
const start = ref.current.selectionStart;
34+
const end = ref.current.selectionEnd;
3535
ref.current.setRangeText(`*${text.slice(start, end)}*`, start, end);
3636
}}
3737
>
3838
<i>I</i>
3939
</button>
4040
<button
4141
onClick={() => {
42-
const start = ref.current.textareaRef.current.selectionStart;
43-
const end = ref.current.textareaRef.current.selectionEnd;
42+
const start = ref.current.selectionStart;
43+
const end = ref.current.selectionEnd;
4444
ref.current.setRangeText(
4545
`~~${text.slice(start, end)}~~`,
4646
start,

0 commit comments

Comments
 (0)