arunghosh / react-pin-input

React PIN / OTP input component
MIT License
106 stars 44 forks source link

Controlled Component #207

Open aintHuman opened 1 year ago

aintHuman commented 1 year ago

I need to include this as a controlled component for use in forms, (inside a wrapped field with something like React Final Form),

As such the initialvalue may change (say for instance via form reset).

Once the object is rendered, change to initialvalue has no effect

Can you please expose a method (like ref.clear()) to set the current value, that way I can use a react side effect to listen to changes in my wrapped component, and then inject these changes into your pin code component.

Thanks.

aintHuman commented 1 year ago

Or alternatively, you could include your own useEffect hook to detect changes to initial value, which would probably be more optimal.

aintHuman commented 1 year ago

For anyone else that needs to do something like this, after reviewing the source code, this is the solution I came up with:

    React.useEffect(() => {
        if(ref && ref?.current){
            const valueArr = (value || '').toString().split('');

            // No changes necessary, short circuit.
            if(isEqual(valueArr, ref.current.values))
                return; 

            // Iterate over each digit updating from valueArray item
            for(let i = 0; i < ref.current.elements.length; i++){
                ref.current.elements[i].update(valueArr[i] || '', true);
            }
        }
    },[value])

Not sure if its what the maintainer would have recommended, but it works for me.

arunghosh commented 1 year ago

@aintHuman Thank you for the suggestion and solution. Will look into this.

aintHuman commented 1 year ago

Also, can you expose the onFocus / onBlur callbacks as arguments in the constructor (which get passed down to each PinItem, and called after your own internal usage), so that I can detect from my parent component, when an individual field has been entered / left.

I need this for a touchpad where there is no keyboard and therefore need to have a up/down button to step the value up / down, or make a keypad to enter the values by touch.

arunghosh commented 1 year ago

@aintHuman Sure. Will consider.