Created
February 7, 2023 20:33
-
-
Save wesleybliss/de6bae860c3525c99557de1d5a094749 to your computer and use it in GitHub Desktop.
Editable text input field in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useState, useEffect, useCallback } from 'react' | |
import cn from 'classnames' | |
import './EditableText.css' | |
const EditableText = ({ | |
className, | |
inputClassName, | |
as: ElementTag = 'span', | |
value, | |
onSubmit, | |
onDoubleClick, | |
}) => { | |
const refNewValue = useRef() | |
const [isEditing, setIsEditing] = useState(false) | |
const [newValue, setNewValue] = useState('') | |
const handleDoubleClick = useCallback(e => { | |
if (isEditing) { | |
setIsEditing(false) | |
} else { | |
setNewValue(value) | |
setIsEditing(true) | |
} | |
if (onDoubleClick) | |
onDoubleClick(e) | |
}, [value, isEditing]) | |
const onKeyUp = useCallback(e => { | |
if (e?.key === 'Enter') { | |
onSubmit(newValue) | |
setIsEditing(false) | |
} | |
if (e?.key === 'Escape') | |
setIsEditing(false) | |
}, [onSubmit, newValue]) | |
useEffect(() => { | |
if (refNewValue.current && isEditing) | |
refNewValue.current?.focus() | |
}, [refNewValue, isEditing]) | |
if (!isEditing) return ( | |
<ElementTag | |
className={className} | |
onDoubleClick={handleDoubleClick}> | |
{value} | |
</ElementTag> | |
) | |
return ( | |
<input | |
ref={refNewValue} | |
className={cn('', inputClassName)} | |
type="text" | |
value={newValue} | |
placeholder="" | |
autoComplete="off" | |
onKeyUp={onKeyUp} | |
onChange={e => setNewValue(e.target.value)} /> | |
) | |
} | |
export default EditableText |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment