How to focus a styled component?

Viewed 4472

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 Answers

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.

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?

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

Related