react-focusit

0.1.0 • Public • Published

react-focusit

React component for focusing element on its 'mount' hook

Usage

import Focus from 'react-focusit';
 
...
 
render() {
    return <Focus><input {...props} /></Focus>;
}

You can use custom focusable component, that implements focus method:

import Focus from 'react-focusit';
import Input from 'some-ui-kit';
 
...
 
render() {
    return (
        <Focus>
            <Input {...props} />
        </Focus>
    );
}

Or use HOC to proxy ref to focusable component:

import Focus from 'react-focusit';
import Input from 'some-ui-kit';
 
function InputHoc({ innerRef }) {
    return <Input ref={innerRef} />;
}
 
...
 
render() {
    return (
        <Focus useInnerRef>
            <InputHoc />
        </Focus>
    );
}
 

You can provide custom ref prop as well:

import Focus from 'react-focusit';
import Input from 'some-ui-kit';
import React from 'react';
 
class InputHoc extends React.Component {
    render() {
        return <Input ref={this.props.customRef} />;
    }
}
 
...
 
render() {
    return (
        <Focus useInnerRef="customRef" innerRef={getFocusableComponent}>
            <InputHoc ref={getComponentRef} />
        </Focus>
    );
}
 

In the example above getFocusableComponent will get Input instance as argument and getComponentRef will get InputHoc instance.

props

prop type default description
innerRef function(instance) provides child instance/element reference. If you don't using useInnerRef prop, use innerRef instead of ref prop directly on child component
preventScroll boolean false parameter for HtmlElement.prototype.focus, preventing scrolling to focused element
withSelection boolean false using with <input />, <textarea /> as focusable component or components with custom select method implementation. Selecting inner text.
children ReactNode must be a single child, we are using React.Children.only to check single react node
useInnerRef boolean\|string false If true using innerRef prop to get focusable component instance, if type string will use custom prop name

Readme

Keywords

Package Sidebar

Install

npm i react-focusit

Weekly Downloads

0

Version

0.1.0

License

MIT

Unpacked Size

10.8 kB

Total Files

5

Last publish

Collaborators

  • vankop