Skip to content

Commit 4bcab8c

Browse files
jmcriffeyKent C. Dodds
authored andcommitted
fix(click): click no longer blurs when focus changes during onClick event (#208)
1 parent df282f9 commit 4bcab8c

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

__tests__/react/click.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,32 @@ describe("userEvent.click", () => {
198198
expect(b).toHaveFocus();
199199
});
200200

201+
it("does not lose focus when click updates focus", () => {
202+
const FocusComponent = () => {
203+
const inputRef = React.useRef();
204+
const focusInput = () => inputRef.current.focus();
205+
206+
return (
207+
<React.Fragment>
208+
<input data-testid="input" ref={inputRef} />
209+
<button onClick={focusInput}>Update Focus</button>
210+
</React.Fragment>
211+
);
212+
};
213+
const { getByTestId, getByText } = render(<FocusComponent />);
214+
215+
const input = getByTestId("input");
216+
const button = getByText("Update Focus");
217+
218+
expect(input).not.toHaveFocus();
219+
220+
userEvent.click(button);
221+
expect(input).toHaveFocus();
222+
223+
userEvent.click(button);
224+
expect(input).toHaveFocus();
225+
});
226+
201227
it.each(["input", "textarea"])(
202228
"gives focus to <%s> when clicking a <label> with htmlFor",
203229
type => {

src/index.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,15 @@ function fireChangeEvent(event) {
9999
event.target.removeEventListener("blur", fireChangeEvent);
100100
}
101101

102+
function blurFocusedElement(element, focusedElement, wasAnotherElementFocused) {
103+
if (
104+
wasAnotherElementFocused &&
105+
element.ownerDocument.activeElement === element
106+
) {
107+
focusedElement.blur();
108+
}
109+
}
110+
102111
const userEvent = {
103112
click(element) {
104113
const focusedElement = element.ownerDocument.activeElement;
@@ -123,7 +132,7 @@ const userEvent = {
123132
clickElement(element);
124133
}
125134

126-
wasAnotherElementFocused && focusedElement.blur();
135+
blurFocusedElement(element, focusedElement, wasAnotherElementFocused);
127136
},
128137

129138
dblClick(element) {
@@ -145,7 +154,7 @@ const userEvent = {
145154
dblClickElement(element);
146155
}
147156

148-
wasAnotherElementFocused && focusedElement.blur();
157+
blurFocusedElement(element, focusedElement, wasAnotherElementFocused);
149158
},
150159

151160
selectOptions(element, values) {
@@ -172,7 +181,7 @@ const userEvent = {
172181
}
173182
}
174183

175-
wasAnotherElementFocused && focusedElement.blur();
184+
blurFocusedElement(element, focusedElement, wasAnotherElementFocused);
176185
},
177186

178187
async type(element, text, userOpts = {}) {

0 commit comments

Comments
 (0)