Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created February 7, 2023 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesleybliss/de6bae860c3525c99557de1d5a094749 to your computer and use it in GitHub Desktop.
Save wesleybliss/de6bae860c3525c99557de1d5a094749 to your computer and use it in GitHub Desktop.
Editable text input field in React
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