File tree Expand file tree Collapse file tree 1 file changed +13
-12
lines changed Expand file tree Collapse file tree 1 file changed +13
-12
lines changed Original file line number Diff line number Diff line change @@ -135,13 +135,19 @@ const ref = React.createRef()
135135## Naïve focus trap implementation
136136
137137``` jsx
138- const firstInput = React .createRef ()
139- initialState = {
140- enabled: false
141- }
138+ import { useRef , useState , useEffect } from ' react'
139+
140+ const firstInput = useRef (null )
141+ const [enabled , setEnabled ] = useState (false )
142+
143+ useEffect (() => {
144+ if (enabled) {
145+ firstInput .current .focus ()
146+ }
147+ }, [enabled])
142148;< FocusWithin
143149 onBlur= {() => {
144- state . enabled && firstInput .current .focus ()
150+ enabled && firstInput .current .focus ()
145151 }}
146152>
147153 < fieldset>
@@ -154,15 +160,10 @@ initialState = {
154160 < button
155161 type= " submit"
156162 onClick= {() => {
157- setState ({
158- enabled: ! state .enabled
159- })
160- if (! state .enabled ) {
161- firstInput .current .focus ()
162- }
163+ setEnabled (! enabled)
163164 }}
164165 >
165- {state . enabled ? ' Disable' : ' Enable' } focus trap
166+ {enabled ? ' Disable' : ' Enable' } focus trap
166167 < / button>
167168 < / fieldset>
168169< / FocusWithin>
You can’t perform that action at this time.
0 commit comments