Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

EditableText.tsx

85 lines1.9 KB

1import { useRef, useState } from 'react'
2import { flushSync } from 'react-dom'
3​
4export function EditableText({
5 fieldName,
6 value,
7 inputClassName,
8 inputLabel,
9 buttonClassName,
10 buttonLabel,
11 onChange,
12 editState,
13}: {
14 fieldName: string
15 value: string
16 inputClassName: string
17 inputLabel: string
18 buttonClassName: string
19 buttonLabel: string
20 onChange: (value: string) => void
21 editState?: [boolean, (value: boolean) => void]
22}) {
23 const localEditState = useState(false)
24 const [edit, setEdit] = editState || localEditState
25 const inputRef = useRef<HTMLInputElement>(null)
26 const buttonRef = useRef<HTMLButtonElement>(null)
27​
28 return edit ? (
29 <form
30 onSubmit={(event) => {
31 event.preventDefault()
32​
33 onChange(inputRef.current!.value)
34​
35 flushSync(() => {
36 setEdit(false)
37 })
38​
39 buttonRef.current?.focus()
40 }}
41 >
42 <input
43 required
44 ref={inputRef}
45 type="text"
46 aria-label={inputLabel}
47 name={fieldName}
48 defaultValue={value}
49 className={inputClassName}
50 onKeyDown={(event) => {
51 if (event.key === 'Escape') {
52 flushSync(() => {
53 setEdit(false)
54 })
55 buttonRef.current?.focus()
56 }
57 }}
58 onBlur={(event) => {
59 if (
60 inputRef.current?.value !== value &&
61 inputRef.current?.value.trim() !== ''
62 ) {
63 onChange(inputRef.current!.value)
64 }
65 setEdit(false)
66 }}
67 />
68 </form>
69 ) : (
70 <button
71 aria-label={buttonLabel}
72 type="button"
73 ref={buttonRef}
74 onClick={() => {
75 flushSync(() => {
76 setEdit(true)
77 })
78 inputRef.current?.select()
79 }}
80 className={buttonClassName}
81 >
82 {value || <span className="text-slate-400 italic">Edit</span>}
83 </button>
84 )