Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Last active August 31, 2022 17:47
Show Gist options
  • Save dr-skot/c1a0ec5b79d19731e13333a26682ceb5 to your computer and use it in GitHub Desktop.
Save dr-skot/c1a0ec5b79d19731e13333a26682ceb5 to your computer and use it in GitHub Desktop.
A Chakra button that inserts text into an input element
import { Button, ButtonProps } from '@chakra-ui/react';
import { RefObject } from 'react';
export type InsertableElement = HTMLInputElement | HTMLTextAreaElement;
function insertStringAtCursor(target: InsertableElement, insertion: string) {
const value = target.value;
const selectionStart = target.selectionStart ?? value.length;
const selectionEnd = target.selectionEnd ?? selectionStart;
const start = value.substring(0, selectionStart);
const end = value.substring(selectionEnd, value.length);
target.value = start + insertion + end;
target.selectionStart = selectionStart + insertion.length;
target.selectionEnd = target.selectionStart;
target.focus();
return target.value;
}
export function InsertButton(
props: ButtonProps & {
insertion: string;
target: RefObject<InsertableElement>;
onInsert?: (value: string) => void;
}
) {
const { insertion, target, onInsert, children, ...rest } = props;
function insert() {
if (target.current) {
const newValue = insertStringAtCursor(target.current, insertion);
onInsert?.(newValue);
}
}
return (
<Button onClick={insert} {...rest}>
{children || insertion}
</Button>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment