Skip to content

Commit fb7d11f

Browse files
authored
Add autofocus feature
2 parents e5af4fc + 233f277 commit fb7d11f

File tree

4 files changed

+11
-1
lines changed

4 files changed

+11
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ export default App
6060
| placeholder | ✔️ | `string` | Input placeholder text |
6161
| disabled | ✔️ | `boolean` | Flag that disables the input element |
6262
| maxLength | ✔️ | `number` | Indicates the maximum number of characters a user can enter |
63+
| autoFocus | ✔️ | `boolean` | Flag to automatically focus the input element on mount |
6364
| updatedContent | ✔️ | `string` | Text injected from parent element into the input as the current value |
6465
| onContentExternalUpdate | ✔️ | `(content) => void` | Method that emits the injected content by the `updatedContent` prop |
6566
| onChange | ✔️ | `(content) => void` | Method that emits the current content as a string |

lib/ContentEditable.tsx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ interface ContentEditableProps {
99
disabled?: boolean
1010
updatedContent?: string
1111
maxLength?: number
12+
autoFocus?: boolean
1213
onChange?: (content: string) => void
1314
onKeyUp?: (e: React.KeyboardEvent) => void
1415
onKeyDown?: (e: React.KeyboardEvent) => void
@@ -35,6 +36,7 @@ const ContentEditable: React.FC<ContentEditableProps> = ({
3536
disabled,
3637
updatedContent,
3738
maxLength,
39+
autoFocus,
3840
onChange,
3941
onKeyUp,
4042
onKeyDown,
@@ -62,6 +64,12 @@ const ContentEditable: React.FC<ContentEditableProps> = ({
6264
}
6365
}, [content, onChange, maxLength])
6466

67+
useEffect(() => {
68+
if (divRef.current && autoFocus) {
69+
divRef.current.focus()
70+
}
71+
}, [autoFocus])
72+
6573
/**
6674
* Checks if the caret is on the last line of a contenteditable element
6775
* @param element - The HTMLDivElement to check

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "react-basic-contenteditable",
33
"description": "React contenteditable component. Super-customizable!",
4-
"version": "1.0.4",
4+
"version": "1.0.5",
55
"type": "module",
66
"main": "dist/main.js",
77
"types": "dist/main.d.ts",

src/App.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ const App = () => {
4646
updatedContent={emptyContent}
4747
onChange={(content) => setContent(content)}
4848
maxLength={100}
49+
autoFocus
4950
onFocus={() => {
5051
setIsFocused(true)
5152
setIsBlurred(false)

0 commit comments

Comments
 (0)