use-react-input
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

use-react-input

npm bundle size Snyk Vulnerabilities for npm package

Simple hooks that handles input onChange function for you.

Motivation

The purpose of use-react-input is to provide simple hooks that relieve you of having to manage onChange functions.

You can use these hooks as is or build more complex libraries on top of that.

✔️ Getting Started

You can install the module via npm or yarn:

npm install use-react-input
yarn add use-react-input

🔨 Usage

useInput

import {useInput} from 'use-react-input'

function App() {
    const [name, inputName] = useInput()
    const [surname, inputSurname] = useInput()

    return (
        <div>
            <div>{inputName}</div>
            <div>{inputSurname}</div>
        </div>
    );
}

Very similar to useState from React, useInput return a couple of values:

  1. The value of the input (you can call it whatever you want)
  2. The <input/> HTML element that you will render inside your JSX (arbitrary name also).

useInput accept 1 object representing any props you would pass into <input/> element.
Example:

const [name, inputName] = useInput({className: 'my-class', placeholder: 'insert something here...'})

type is an input property that represent the type of the input. Here is the whole list.
If you do not specify any type, default is text.

Here's how you can specify different type:

const [number, inputNumber] = useInput({type: 'number', placeholder: 'insert a number here...'})

You can also specify a default value:

const [number, inputNumber] = useInput({
    type: 'number',
    defaultValue: 30,
    placeholder: 'insert a number here...'
})

useInputCheckbox

useInputCheckbox accept almost the same props of useInput, except that the type is fixed to checkbox, so you can't change it.

Input checkboxes does not accept defaultValue, but accept defaultChecked instead:

const [checkbox, inputCheckbox] = useInputCheckbox({
    defaultChecked: true,
})

if not specified, the default value of checkbox is false.

More examples available on demo/src/App.js

Comparison

Here's how you would handle 2 input text in React without any external libraries:

import {useState} from 'react';

function App() {
    const [name, setName] = useState()
    const [surname, setSurname] = useState()

    const handleChangeName = (event) => {
        setName(event.target.value)
    }
    const handleChangeSurname = (event) => {
        setSurname(event.target.value)
    }

    return (
        <form onSubmit={(event) => {
            alert('A name was submitted: ' + name + ' ' + surname);
            event.preventDefault();
        }}>
            <label>
                Name:
                <input type="text" onChange={handleChangeName}/>
            </label>
            <label>
                Surname:
                <input type="text" onChange={handleChangeSurname}/>
            </label>
            <input type="submit" value="Submit"/>
        </form>
    );
}

you could write the same App with few lines of code using useInput:

import {useInput} from 'use-react-input';

function App() {
    const [name, inputName] = useInput()
    const [surname, inputSurname] = useInput()

    return (
        <form onSubmit={(event) => {
            alert('A name was submitted: ' + name + ' ' + surname);
            event.preventDefault();
        }}>
            <label>
                Name:
                {inputName}
            </label>
            <label>
                Surname:
                {inputSurname}
            </label>
            <input type="submit" value="Submit"/>
        </form>
    );
}

Optimize Performance

You have 2 different ways to optimize your input props.
Do performance optimization when you are sure about your input props will not change.

  1. Declare object props outside of render cycle:
import {useInput} from 'use-react-input'

const nameProps = {className: 'my-class'}
const surnameProps = {className: 'my-class'}

function App() {
    const [name, inputName] = useInput(nameProps)
    const [surname, inputSurname] = useInput(surnameProps)

    return (
        <div>
            <div>{inputName}</div>
            <div>{inputSurname}</div>
        </div>
    );
}
  1. Use useMemo to memoize the object:
import {useMemo} from "react"
import {useInput} from 'use-react-input'

function App() {
    const [name, inputName] = useInput(
        useMemo(() => ({
            className: 'my-class'
        }), [])
    )
    const [surname, inputSurname] = useInput(
        useMemo(() => ({
            className: 'my-class'
        }), [])
    )

    return (
        <div>
            <div>{inputName}</div>
            <div>{inputSurname}</div>
        </div>
    );
}

additional onChange (available from v1.1.0)

You may want to add additional onChange functions when you write into input.
You can do that by adding your onChange from object. Note that you will get the value as always.
Example:

const [surname, inputSurname] = useInput({
    defaultValue: test,
   onChange: (e) => console.log("print the event: ", e)
})

same for useInputCheckbox

const [checkbox, inputCheckbox] = useInputCheckbox({
    defaultChecked: true,
   onChange: (e) => {
        console.log("additional function. Print event: ", e)
   }
})

💻 Demo

Live Demo

📁 Project Structure

The project includes a demo folder initialized with Create React App.

When you run the command build from first-level package.json, a dist and a lib folder will be generated.

The lib folder will be placed automatically into the demo project.

You can move into demo directory and start project from its own package.json script, just like any other Create React App project.

Contributing and Support

Contributions of any kind are welcome.

If this package was helpful to you, please consider putting a star on the GitHub project.

License

MIT

Package Sidebar

Install

npm i use-react-input

Weekly Downloads

0

Version

1.2.1

License

MIT

Unpacked Size

10.8 kB

Total Files

7

Last publish

Collaborators

  • minu1994