Skip to content

Commit

Permalink
whoops
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Feb 28, 2024
1 parent 076f084 commit e21638a
Showing 1 changed file with 21 additions and 17 deletions.
38 changes: 21 additions & 17 deletions exercises/08.focus/01.solution/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useRef, useState } from 'react'
import { flushSync } from 'react-dom'
import * as ReactDOM from 'react-dom/client'

function EditableText({
Expand All @@ -17,18 +18,18 @@ function EditableText({
const [edit, setEdit] = useState(false)
const [value, setValue] = useState(initialValue)
const inputRef = useRef<HTMLInputElement>(null)
// 🐨 add a button ref here
const buttonRef = useRef<HTMLButtonElement>(null)

return edit ? (
<form
method="post"
onSubmit={event => {
event.preventDefault()
// here's where you'd send the updated value to the server
// 🐨 wrap these calls in a flushSync
setValue(inputRef.current?.value ?? '')
setEdit(false)
// 🐨 after flushSync, focus the button with the button ref
flushSync(() => {
setValue(inputRef.current?.value ?? '')
setEdit(false)
})
buttonRef.current?.focus()
}}
>
<input
Expand All @@ -41,28 +42,31 @@ function EditableText({
defaultValue={value}
onKeyDown={event => {
if (event.key === 'Escape') {
// 🐨 wrap this in a flushSync
setEdit(false)
// 🐨 after the flushSync, focus the button
flushSync(() => {
setEdit(false)
})
buttonRef.current?.focus()
}
}}
onBlur={event => {
// 🐨 wrap these in a flushSync
setValue(event.currentTarget.value)
setEdit(false)
// 🐨 after the flushSync, focus the button
flushSync(() => {
setValue(event.currentTarget.value)
setEdit(false)
})
buttonRef.current?.focus()
}}
/>
</form>
) : (
<button
aria-label={buttonLabel}
// 🐨 add a ref prop for the button
ref={buttonRef}
type="button"
onClick={() => {
// 🐨 wrap this in a flushSync
setEdit(true)
// 🐨 after the flushSync, select all the text of the input
flushSync(() => {
setEdit(true)
})
inputRef.current?.select()
}}
>
{value || 'Edit'}
Expand Down

0 comments on commit e21638a

Please sign in to comment.