npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-react-input

v1.2.1

Published

Simple hooks that handles input onChange function for you.

Downloads

8

Readme

use-react-input

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