问题
All most all the articles and examples about setting focus are explained using input element. It works well with input element but how to set focus to a div element using React useRef and useEffect hooks?
How to test it using toHaveFocus
of react-testing-library?
回答1:
After searching for a while and wasting quite a bit of time, I was able to do it. Sharing it here for friends!!
Component file SetFocusToDivComponent.js
import React, { useRef, useEffect } from 'react';
export default function SetFocusToDivComponent() {
const containerRef = useRef(null);
useEffect(() => {
containerRef.current.focus();
});
return (
<div
data-test={'container'}
ref={errorDisplayWrapperRef}
tabIndex={-1}
>
Hello There!!
</div>
);
}
Test file SetFocusToDivComponent.tests.js
import React from 'react';
import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import SetFocusToDivComponent from './SetFocusToDivComponent';
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
test('setting focus', () => {
act(() => {
ReactDOM.render(<SetFocusToDivComponent />, container);
});
expect(container.querySelector('div[data-test="container"]')).toHaveFocus();
});
If you are using a styled div instead of plain html div, then use innerRef
instead of ref
const StyledDiv = styled.div`
border-radius: 0 0 5px 5px;
border: 1px solid green;
`;
<StyledDiv
data-test={'container'}
innerRef={errorDisplayWrapperRef}
tabIndex={-1}
>
Hello There!!
</StyledDiv>
PS: Don't forget tabIndex
来源:https://stackoverflow.com/questions/55264417/how-to-set-focus-to-a-div-element-in-a-react-component-using-useeffect-and-usere