Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controlled Component #207

Open
aintHuman opened this issue Feb 21, 2023 · 5 comments
Open

Controlled Component #207

aintHuman opened this issue Feb 21, 2023 · 5 comments

Comments

@aintHuman
Copy link

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
Copy link
Author

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

@aintHuman
Copy link
Author

aintHuman commented Feb 21, 2023

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
Copy link
Owner

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

@aintHuman
Copy link
Author

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
Copy link
Owner

@aintHuman Sure. Will consider.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants