Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus a styled component?

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?

like image 682
JoeTidee Avatar asked Sep 13 '17 15:09

JoeTidee


1 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.

like image 194
probablyup Avatar answered Oct 16 '22 17:10

probablyup