Search code examples
reactjsmodal-dialogfocusaccessibilitystyled-components

How to focus trap with styled-components? How to access classname from styled-components?


I'm currently using styled-components 5.0.1 with React. https://styled-components.com/

For context, my goal is to focus trap within a modal.

My problem is that classnames are randomly generated from styled-components so I'm not able to access these DOM nodes with querySelector. My other problem is that I'm not able to use React ref forwarding since I would have to do a lot of ref forwarding between component trees.

Is there a way to access the classname that is generated from styled-components? If so, I can use querySelector and go about the usual way of focus trapping by accessing the DOM nodes through querySelector.


Solution

  • I was able to solve this issue by accessing the DOM nodes with using a data- attribute.

    For example,

    const myComponent = styled.div`
      // ...styles here
    `;
    
    const foo = () => (
      <myComponent
        data-foo-bar="foobar"
      />
    );
    
    console.log(document.querySelector('[data-a11y-id="HeaderNavBar-SearchButton"]');
    // returns the DOM element for myComponent