How to focus a styled component?

5.4k Views Asked by At

I have a styled component:

const StyledComponent = styled.div`
    ...
`;

and I want to focus it when the component that uses it is mounted:

class someComponent extends React.Component {
    componentDidMount() {
        this.sc.focus();
    }

    render() {
        return (
            <StyledComponent innerRef={(elem) => { this.sc = elem; }}>
                ...
            </StyledComponent>
        );
    }
}

this technique does not work - is there a solution for this?

3

There are 3 best solutions below

0
currenthandle On

Try passing the autoFocus prop to your StyledComponent like <StyledComponent autoFocus />.

1
jaysonder On

This link has an example with both React 16 React.createRef() and the callback method.

Have you tried setting the autoFocus attribute, or is that not fit for your use case?

1
probablyup On

You can't focus non-interactive elements without the use of tabIndex ("tabindex" in normal HTML). The "div" element is considered non-interactive (unlike anchor links "a" and button controls "button".)

If you want to be able to focus this element, you'll need to add a tabIndex prop. You can use .attrs if desired to have it be added automatically so you don't need to write the prop every time.