Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access input reference from another file using Unform?

I’m trying to use unform with the following structure:

Component/inputRadio.ts:

export const TextInputInput: React.FC<TextInputInputProps> = ({ name, ...props }) => {
    const inputRef = useRef<HTMLInputElement>(null);
    const { fieldName, registerField } = useField(name!);

    useEffect(() => {
        registerField({
            name: fieldName,
            ref: inputRef.current,
            path: 'value',
        });
    }, [fieldName, registerField]);
        
    return(
        <InputCss ref={inputRef} className={clsx(InputCss)} {...props} />
    )
}

In another file this is my submit function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Login: React.FC = () => {
const formRef = useRef<FormHandles>(null);

const handleSubmit = useCallback(
    async (data: SignInFormData) => { 
      try {    
        console.log(data);
      } catch (err) {    
        console.log(err);
      }
    },
    [],
);

return(

        <Form ref={formRef} onSubmit={handleSubmit} >
                    <TextInputInput 
                        type='text'  
                        id="text" 
                        name='cpf'
                        placeholder='000.000.000-00' 
                    />

                    <FormatedTextInput 
                        type="password" 
                        id='password'
                        name='password'
                        placeholder='********'
                    />
            <Button type='submit'>Entrar</Button>
        </Form>
    )
}

export default Login;

how can I manipulate the value outside the component? I’m already using useRef inside the component with this "standard" Unform structure. How do you change or get the value in another file import?

specifically I want to get one field value when click in another button, this before the submit function.

I dont want to use document.getElementById().

>Solution :

You can use formRef.current.getFieldValue.

For example, if you want to get the value of cpf, you can use formRef.current.getFieldValue('cpf').

Use formRef.current.getData() if you want to access all values.

These are also documented in the unform guides.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading