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

react-input-state

v1.1.7

Published

HTML input|select|textarea state management, mask, validation and utilities

Downloads

101

Readme

React Input State

<input>, <textarea> and <select> state management, content validator, sanitizer, mask, currency, content replacer and virtual data

Installing

Yarn

yarn add react-input-state

Npm

npm i react-input-state

useInputState hook

  • Set the element root containing the inputs, selects and textarea
  • (optional) Set the submit element ref (button or other), it will be disabled if invalid data has be detected
  • (optional) Dependency list
useInputState(ref, config, deps)
import useInputState from 'react-input-state'

const MyApp = () => {
    const myRootElement = createRef<HTMLDivElement>()
    const submitButton = createRef<HTMLButtonElement>()

    const [isLoading, setIsLoading] = useState<boolean>(false)

    // second and third argument is optional
    const [state] = useInputState(myRootElement, {

        initialState: {},
        submitButton,
        onValidate: (name, isValid, validationType) => {}
        invalidClasses: ''

    }, [isLoading])

    const handleSubmit = () => {
        if (!state.isValid) {
            return
        }
        sendDataToBackend('/endpoint', state.values)
    }

    // SOME EXAMPLES, see more below

    return <div ref={myRef}>
       <input type="text" name="any" required

        data-regex-validation="YOUR_REGEX_PATTERN"
        data-validators="credit_card,cpf,cnpj"

       />
       {/* You do not need to hide this div, it will be made automatically */}
       <div data-error-for="any">Invalid data!</div>

        {/* transforming text */}

       <input type="email" name="email" required

        data-validators="email"
        data-transform="lowercase,trim"

       />
       <div data-error-for="email">Invalid email!</div>

       {/* mask, use 9 for numbers */}

       <input type="text" name="date" required

        data-mask="99/99/9999"

       />

        {/* check if given password is strong */}

       <input type="password" name="password" required

        data-validators="strong_password"

       />
       <div data-error-for="password">Please provide a strong password!</div>

       {/* Set data-private and it will not be returned in state.values */}
       <input type="text" name="my-any-name" required

        data-private="true"

       />

      {/* Validating conditionally */}

       <input type="text" name="any-name"

        data-greater-or-equal="5"

       />

       {/* this field will be ignored */}

       <input type="text" name="any-name"

        data-ignore="true"

       />

       {/* You can work with select and textarea elements as well */}

       <select name="my-select" required>
            <option value="">Choose</option>
            <option value="any">Text</option>
            <option value="any2">Text2</option>
       </select>

       <textarea name="my-textarea" required></textarea>

       <button ref={submitButton} onClick={handleSubmit}>Submit</button>
    </div>
}

export default MyApp

data-validators

You can combine any validator separating it by comma

<input type="text" name="any" data-validators="credit_card,ean,iban" />

Possible values

email - cpf - cnpj - bic_swift - btc - credit_card - ean - iban - imei - json - magnet_uri - numeric - octal - strong_password

data-transform

<input type="text" name="any" data-transform="trim,urlsafe" />

Possible values

lowercase - uppercase - titlecase - trim - urlsafe

data-mask

<input type="text" name="any" data-mask="(99) 99999-9999" />
  • 9 - accept digit
  • A - accept alpha
  • S - accept alphanumeric

Currency (data-currency)

<input type="text" name="any" data-currency="true" />

See below all currency data optional attributes and its default values

data-prefix=""
data-decimal-separator=","
data-group-separator="."
data-precision="2"

data-remove

Regular expression pattern to remove unwanted characters

<input type="text" name="any" data-remove="\D+" />

data-regex-validation

Regular expression pattern to validate content based on a regex pattern

<input type="text" name="any" data-regex-validation="^[a-z]+$" />

data-reload-component

Determine if you want to reload the component on input/select changes

<select name="any" data-reload-component="true"></select>
<input type="text" name="any" data-reload-component="true" />

Conditional validators

data-equals and data-not-equals accept string or numbers as well

<input type="text" name="any" data-equals="..." />
<input type="text" name="any" data-greater-or-equal="5" />
<input type="text" name="any" data-greater-than="5" />
<input type="text" name="any" data-less-or-equal="5" />
<input type="text" name="any" data-less-than="5" />
<input type="text" name="any" data-not-equals="..." />

This feature does not check types, 1 (number) will be equals to "1" (string)

data-private

This feature removes the input/select value from state values

<select name="any" data-private="true"></select>
<input type="text" name="any" data-private="true" />

Private values can be obtained calling myStateName.privateValues

const [myStateName] = useInputState(rootRef)

// private values
myStateName.privateValues

data-ignore

If you don't want the input/select to be managed by this lib

<select name="any" data-ignore="true"></select>
<input type="text" name="any" data-ignore="true" />

Setting value programmatically

state.setValue('name', anyData)

caution: If the input or select does not exists, an Error will be thrown, you can surround it by try / catch

Individual values

const value = state.value('name')

Setting initialState after initialization

state.setInitialState({})

Reloader

The second entry returned by useInputState is a component reloader utility, you can use it in some specific situations

const MyApp = () => {
    const [state, reloader] = useInputState(myRootElement)

    return (
        <select
            name="any"
            onChange={() => {
                if (state.value('any') == 'any_other_value') {
                    reloader.reload()
                }
            }}
        >
            <option></option>
        </select>
    )
}

Virtual Values

Use virtual values when you need to set values that does't have fields for them

setVirtual(name: string, value: any, private: boolean = false)

Set third argument to true (private) if you don't want to get the value in state.values

Virtual individual values

const value = state.virtual('my-value')

Setting virtual state after initialization

state.setVirtualState({})

Delete a value from virtual state

state.deleteVirtual('my-name', true)

The second argument is optional, it determines if your want the component to be reloaded, default value is false

Configuration properties

const MyApp = () => {
    // Second hook argument
    const [state, reloader] = useInputState(myRootElement, {
            initialState: {}
            /**
             * zero = forever
             */
            closeErrorMessageMilliseconds: 3000

            /**
             * Reference
             */
            submitButton:

            /**
             * Called when validating a field
             */
            onValidate: (name, isValid, validationType) => {}

            /**
             * Add classes to input when it contains invalid data
             */
            invalidClasses: '...',

             virtualState: {}
    })

    return null
}

Configuration properties GLOBAL

import { ReactInputStateConfig } from 'react-input-state'

ReactInputStateConfig.closeErrorMessageMilliseconds = 3000
ReactInputStateConfig.invalidClasses = '...'
//....