GOOGLE ADS

domingo, 24 de abril de 2022

No se puede deshabilitar el botón fuera de Formik usando innerRef

Estoy tratando de usar innerRef en Formik para obtener isValid y sucio fuera de Formik para deshabilitar el botón de envío. He adjuntado la codificación a continuación.

import React, { useRef } from "react";
import { Button, Checkbox, Select } from "antd";
import { useTranslation } from "react-i18next";
import { OverlayScrollbarsComponent } from "overlayscrollbars-react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { FloatLabel } from "../../../UIComponent/index";
import { roles } from "../../Roles/sample";
import { filter, sort } from "../../../_util/select";
const AddEditUser = ({ setVisible, visible, users }) => {
const { t } = useTranslation();
const { Option } = Select;
let formRef = useRef({});
const userValidationSchema = Yup.object().shape({
firstName: Yup.string().required("First Name is Required."),
userName: Yup.string().required("User Name is Required.")
.test("username-unique", "User Name Already Exist.",
(value) => users.find(el => el.name?.toLowerCase() === value?.toLowerCase())? false: true),
password: Yup.string().required("Password is Required.")
});
return <div className="formContainer h-100">
<OverlayScrollbarsComponent className="formBody">
<Formik
innerRef={formRef}
initialValues={{
firstName: "",
lastName: "",
userName: "",
role: "",
password: ""
}}
validationSchema={userValidationSchema}
onSubmit={async values => { }}
onChange={()=> console.log("sss")}
>
{({
values,
setFieldValue,
setFieldTouched,
errors,
touched
}) => <Form noValidate>
<div className="innerContainer row">
<div className="col-12 mb-2 ">
<FloatLabel label="First Name" name="firstName" value={values.firstName}>
<Field
type="text"
className="w-100 form-control"
name="firstName" />
<ErrorMessage
name="firstName"
component="span"
className="errorMessage"
/>
</FloatLabel>
</div>
<div className="col-12 mb-2">
<FloatLabel label="Last Name" name="lastName" value={values.lastName}>
<Field
type="text"
className="w-100 form-control"
name="lastName" />
<ErrorMessage
name="lastName"
component="span"
className="errorMessage"
/>
</FloatLabel>
</div>
<div className="col-12 mb-2">
<FloatLabel label="User Name" name="userName" value={values.userName}>
<Field
type="text"
className="w-100 form-control"
name="userName" />
<ErrorMessage
name="userName"
component="span"
className="errorMessage"
/>
</FloatLabel>
</div>

<div className="col-12 mb-2">
<FloatLabel label="Password" name="password" value={values.password}>
<Field
type="password"
className="w-100 form-control"
name="password" />
<ErrorMessage
name="password"
component="span"
className="errorMessage"
/>
</FloatLabel>
</div>
</Form>
}
</Formik>
</OverlayScrollbarsComponent>
<footer>
<Button className="button"
disabled={!(formRef.isValid && formRef.dirty)}>
{t("submit")}
</Button>
</footer>
</div>
};
export default AddEditUser;

En este ejemplo anterior, estoy usando innerRef en Formik para obtener sus propiedades del formulario para deshabilitar el botón pero no funciona como se esperaba. Traté de poner la consola dentro de innerRef. Vi que el valor se está actualizando.

 innerRef={(ref)=> {
console.log(ref); // here I'm seeing the value updating whenever the form properties
value changes
formRef = ref;
}}

pero sin deshabilitar el botón. ¿Alguien puede ayudar a obtener propiedades de formik para deshabilitar el botón Enviar?


Solución del problema

Si lee https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs cuidadosamente. Notará que para hacer uso de la referencia, debe usar ref.current.

Así disabled={!(formRef.isValid && formRef.dirty)}>debería serdisabled={!(formRef.current.isValid && formRef.current.dirty)}>

No hay comentarios:

Publicar un comentario

Regla de Firestore para acceder a la generación de subcolección Permisos faltantes o insuficientes

Tengo problemas con las reglas de Firestore para permitir el acceso a algunos recursos en una subcolección. Tengo algunos requests document...