Description
I discovered a strange behavior in the FocusWithin
component when I was building a custom input component. When I clicked outside of the wrapper element of the custom inputs, the lastly activated input kept the focus style.
After that, I tried one of the examples from the documentation in a newly created react app and the FocusWithin
component behaved the exact same that I experienced earlier.
Reproduction steps:
- Create a new react app using the
create-react-app
command. - Paste the attached code snippet to the
App.js
file (you can find it at the bottom of the issue). - Start the application.
- Click into one of the inputs.
- Try to click outside of the
form
element.
Current result: If you click outside of the form
horizontally, it works fine, because the area is in the wrapper element of the form, but if you click outside vertically, that space is out of the wrapper component, so the form
will keep the focused state.
Expected result: The form
should lose the focus that when the user clicks outside of it.
Code snippet
import React from 'react';
import { FocusWithin } from '@component-driven/react-focus-within';
function App() {
return (
<div className="App">
<FocusWithin
onFocus={() => {
console.log('Received focus')
}}
onBlur={() => {
console.log('Lost focus')
}}
>
{({ focused, getRef }) => (
<form style={{ margin: '100px auto', width: '300px' }}>
<fieldset
ref={getRef}
style={{ borderColor: focused ? 'blue' : '#999' }}
>
<div>
<label htmlFor="input1">First input</label>
<input
id="input1"
type="text"
placeholder="Click to activate first input"
/>
</div>
<div>
<label htmlFor="input2">First input</label>
<input
id="input2"
type="text"
placeholder="Use Tab to activate next input"
/>
</div>
<button type="submit">Submit</button>
<p style={{ color: focused ? 'danger' : 'text' }}>
{focused ? 'Focus is inside' : 'No focus here'}
</p>
</fieldset>
</form>
)}
</FocusWithin>
</div>
);
}
export default App;