How to set focus to a div element in a react component using useEffect and useRef hooks? And how to test it?

£可爱£侵袭症+ 提交于 2020-03-03 07:55:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!