Skip to content

Commit

Permalink
fix(editable): set focus on EditableInput when startsWithEditView is …
Browse files Browse the repository at this point in the history
…true
  • Loading branch information
primos63 committed Dec 17, 2021
1 parent b983e4c commit 032c2e5
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .changeset/smart-apes-divide.md
@@ -0,0 +1,6 @@
---
"@chakra-ui/editable": patch
---

When the Editable component has its startsWithEditView set to true, then focus
should be set to the EditableInput element when the component is mounted.
9 changes: 9 additions & 0 deletions packages/editable/src/use-editable.ts
Expand Up @@ -2,6 +2,7 @@ import {
useControllableState,
useFocusOnPointerDown,
useUpdateEffect,
useSafeLayoutEffect,
} from "@chakra-ui/hooks"
import { EventKeyMap, mergeRefs, PropGetter } from "@chakra-ui/react-utils"
import {
Expand Down Expand Up @@ -127,6 +128,14 @@ export function useEditable(props: UseEditableProps = {}) {

const isInteractive = !isEditing || !isDisabled

useSafeLayoutEffect(() => {
if (isEditing) {
focus(inputRef.current, {
selectTextIfInput: selectAllOnFocus,
})
}
}, [])

useUpdateEffect(() => {
if (!isEditing) {
focus(editButtonRef.current)
Expand Down
13 changes: 13 additions & 0 deletions packages/editable/tests/editable.test.tsx
Expand Up @@ -211,3 +211,16 @@ test("can submit on blur", () => {
fireEvent.blur(input)
expect(onSubmit).toHaveBeenCalledWith("testing")
})

test("startWithEditView when true focuses on the input ", () => {
render(
<Editable startWithEditView={true} defaultValue="Chakra testing">
<EditablePreview />
<EditableInput data-testid="input" />
</Editable>,
)

const input = screen.getByTestId("input")

expect(document.activeElement === input).toBe(true)
})

0 comments on commit 032c2e5

Please sign in to comment.