This is probably not the best place to post this question but where, then?
The code below is taken from Formik's overview page and I'm very confused about the onSubmit handlers:
The form element has an onSubmit property that refers to handleSubmit which is passed on that anonymous function : <form onSubmit={handleSubmit}>. Where does that come from?
The Formik component has an onSubmit property as well:
onSubmit={(values, { setSubmitting }) => { ... }
How do these relate to each other? What is going on?
import React from 'react';
import { Formik } from 'formik';
const Basic = () => (
<div>
<h1>Anywhere in your app!</h1>
<Formik
initialValues={{ email: '', password: '' }}
validate={values => {
let errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (
!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
) {
errors.email = 'Invalid email address';
}
return errors;
}}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
/* and other goodies */
}) => (
<form onSubmit={handleSubmit}>
<input
type="email"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
/>
{errors.email && touched.email && errors.email}
<input
type="password"
name="password"
onChange={handleChange}
onBlur={handleBlur}
value={values.password}
/>
{errors.password && touched.password && errors.password}
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</form>
)}
</Formik>
</div>
);
export default Basic;
The component takes onSubmit as a prop where you can execute code you want to perform when you submit your form. This prop is also given some arguments such as values (values of the form) for you to use in your onSubmit function.
The handleSubmit form is auto generated from the Formik library that automates some common form logics explained here. The handleSubmit will automatically execute onSubmit function mentioned above as part of its phases (pre-submit, validation, submission). Hope that answers your question!
Related
I'm trying to create an image upload on my form. The problem is when I try to change the value to the actual uploaded file. I am trying to use setFieldValue, but it says it is undefined. Below is the code. Any ideas why it is undefined? I thought it comes with Formik.
import { Formik } from 'formik';
const AddProduct = (props) => {
return (
<Formik
initialValues={{
serviceImage: null
}}
onSubmit={(values) => {
console.log(values);
}}
>
{({
errors,
handleBlur,
handleChange,
handleSubmit,
setFieldValue,
isSubmitting,
touched,
values,
formProps
}) => (
<form onSubmit={handleSubmit}>
<TextField
error={Boolean(touched.serviceName && errors.serviceName)}
fullWidth
helperText={touched.serviceName && errors.serviceName}
label="Service name"
margin="normal"
name="serviceName"
onBlur={handleBlur}
onChange={handleChange}
value={values.serviceName}
/>
<Button>
<input
id="file"
name="serviceImage"
value={values.serviceImage}
type="file"
onChange={(event) => formProps.setFieldValue('serviceImage', event.target)
}
/>
Add an Image
</Button>
<Button
type="submit" >
Post this service on the Events Platform
</Button>
</form>
)}
</Formik>
);
};
You already declare setFieldValue in your formik callback function
So change it to:
<input
id="file"
name="serviceImage"
value={values.serviceImage}
type="file"
onChange={event => setFieldValue('serviceImage', event.currentTarget.files[0])}
/>;
Hello my great teachers of StackOverflow. I'm going through ben awads fullstack tutorial and am trying to add an image upload feature to create post. Looks like everything works well, inserts posts (including image) into db. However, after submitting my form, it wont send me to the home page (stays on the same page with current values inserted). It is set so that if there are no errors, route me to the homepage. Im assumming i have no errors cause the post inserts into database. Any help will be greatly appreciated.
const CreatePost: React.FC<{}> = ({}) => {
const router = useRouter();
const [createPost] = useCreatePostMutation();
return (
<Layout>
<Formik
initialValues={{ title: "", text: "", file: null }}
onSubmit={async (values) => {
console.log(values);
const { errors } = await createPost({
variables: values,
});
if (!errors) {
router.push("/");
}
}}
>
{({ isSubmitting, setFieldValue }) => (
<Form>
<InputField name="title" placeholder="title" label="Title" />
<Box mt={4}>
<InputField name="text" placeholder="text..." label="Body" />
</Box>
<Input
mt={4}
required
type="file"
name="file"
id="file"
onChange={(event) => {
setFieldValue("file", event.currentTarget.files[0]);
}}
/>
<Button mt={5} type="submit" isLoading={isSubmitting}>
create post
</Button>
</Form>
)}
</Formik>
</Layout>
);
};
You can use router.push hook.
You need to pass validate function as props to Fomik to prevent submitting only with 2 fields. I have added a basic validate object. But you can use Yup package also. Formik will return an error object inside the form and you need to make sure form does not get submitted in error state. For that get the errors object and as you are using custom Button component pass true/false by checking if any errors exist. I added the code.
You can get more details here.
router.push("/home");
.....
const validate={values => {
const errors = {};
if (!values.title) {
errors.email = 'Required';
}
if (!values.text) {
errors.text= 'Required';
}
if (!values.file) {
errors.file= 'Required';
}
return errors;
}}
<Formik
initialValues={{ title: "", text: "", file: null }}
validate
onSubmit={async (values) => {
.......
{({ isSubmitting, setFieldValue, errors }) => (
..........
<Button mt={5} type="submit" isLoading={isSubmitting} isFormValid={!Object.values(errors).find(e => e)}>
create post
</Button>
I have formik form build on the react-boostrap form. I have a custom onchange for handling the inputs. The issue is that validation error throw even if there is a value in the form field. Also, If some value is typed then error message is not gone. I guess the validation is not working at all. Please help me on this.
This is the code for react-bootstrap form https://react-bootstrap.github.io/components/forms/#forms-validation-libraries
import React from "react";
import * as yup from "yup";
export default function StepByStepForm() {
const [myForm, setMyForm] = useState({});
const handleInput = (e) => {
const value = e.target.value;
const name = e.target.name;
setMyForm((prev) => ({
...prev,
[name]: value,
}));
};
const form1schema = yup.object({
company_name: yup.string().required(),
});
function Step1Form() {
return (
<Formik validationSchema={form1schema}>
{({
touched,
isValid,
isInvalid,
errors,
handleBlur,
handleChange,
values,
validateForm,
}) => (
<Form noValidate className="formstep1">
<Form.Group controlId="addCompany">
<Form.Label>Company Name*</Form.Label>
<Form.Control
name="company_name"
type="text"
value={myForm.company_name}
onChange={handleInput} // have my custom handling
isInvalid={!!errors.company_name}
/>
<Form.Control.Feedback type="invalid">
{errors.company_name}
</Form.Control.Feedback>
</Form.Group>
<div className="step-progress-btn">
<Button variant="primary" onClick={() => validateForm()}>
Validate
</Button>
</div>
</Form>
)}
</Formik>
);
}
return <div>Step1Form()</div>;
}
Your custom onChange={handleInput} function never passes the value to Formik.
Formik internally keeps track of your form values, so you don't need to add it using the useState method like you are now (const [myForm, setMyForm] = useState({});).
When you add a custom onChange to your form, you change your component state, while Formik's state never updates, so Yup does not have a value to validate.
If you add this just below your closing </Form> tag, you will see Formik never reads your form's updated values:
<pre>
{JSON.stringify(
{
touched,
isValid,
isInvalid,
errors,
handleBlur,
handleChange,
values,
validateForm
},
null,
2
)}
</pre>
The issue was that Formik-Yup needed the onChange={handleChange} to validate
If you have custom or additional functionality on top of handleChange then you need to add the eventlistener on top of handlechange
import React from "react";
import * as yup from "yup";
export default function StepByStepForm() {
const [myForm, setMyForm] = useState({});
const handleInput = (e) => {
const value = e.target.value;
const name = e.target.name;
setMyForm((prev) => ({
...prev,
[name]: value,
}));
};
const form1schema = yup.object({
company_name: yup.string().required(),
});
function Step1Form() {
return (
<Formik validationSchema={form1schema}>
{({
touched,
isValid,
isInvalid,
errors,
handleBlur,
handleChange,
values,
validateForm,
}) => (
<Form noValidate className="formstep1">
<Form.Group controlId="addCompany">
<Form.Label>Company Name*</Form.Label>
<Form.Control
name="company_name"
type="text"
value={myForm.company_name}
onChange={(e) => {
handleChange(e);
handleInput(e);
}}
isInvalid={!!errors.company_name}
/>
<Form.Control.Feedback type="invalid">
{errors.company_name}
</Form.Control.Feedback>
</Form.Group>
<div className="step-progress-btn">
<Button variant="primary" onClick={() => validateForm()}>
Validate
</Button>
</div>
</Form>
)}
</Formik>
);
}
return <div>Step1Form()</div>;
}
Code below validate when submit and onFocusOut of textbox fine, What I expect it to trigger validation first reload of the page with initial values.
Tried validateOnMount, as well as others but not worked.
Whats missing here?
const RoleValidationSchema = Yup.object().shape({
Adi: Yup.string()
.min(2, "En az 2 karakter olmalıdır")
.max(30, "En fazla 30 karakter olmalıdır")
.required("Gerekli!")
})
const Role = (props) => {
return (
<div>
<Formik
onSubmit={(values, { validate }) => {
debugger
validate(values);
alert("Submietted!")
props.handleFormSubmit()
}}
initialValues={{
Adi: "d"
}}
validationSchema={RoleValidationSchema}
validateOnMount={true}
validateOnChange={true}
validateOnBlur={true}
render={({ errors, touched, setFieldValue, ...rest }) => {
debugger
return (
<Form>
<Row>
<Col sm="12">
<Label for="Adi">Rol Adi</Label>
<FormGroup className="position-relative">
<Field
autoComplete="off"
id="Adi"
className="form-control"
name="Adi"
type="text"
/>
<ErrorMessage name="Adi">
{(msg) => (
<div className="field-error text-danger">{msg}</div>
)}
</ErrorMessage>
</FormGroup>
</Col>
<Tree dataSource={treeData} targetKeys={targetKeys} expandKeys={[]} onChange={onChange} />
</Row>
<button type="submit" className="btn btn-success" > Kaydet</button>
</Form>
)
}}
/>
</div>
)
}
This worked for me to show validation error on form load.
useEffect(() => {
if (formRef.current) {
formRef.current.validateForm()
}
}, [])
Try to add enableReinitialize Prop to your Formik Component
<Formik
enableReinitialize
......
/>
I had a bit specific case with dynamic Yup schema. Schema was generated based on API data. And validateOnMount was failing as when component was mounted there was no schema yet (API response not received yet).
I end up with something like this.
Inside component I used useEffect. Notice: I used useRef to be able to reference Formik outside of form.
useEffect(() => {
if (formRef.current) {
// check that schema was generated based on API response
if(Object.keys(dynamicValidationSchema).length != 0){
formRef.current.validateForm()
}
}
}, [initialData, dynamicValidationSchema])
Formik:
<Formik
innerRef={formRef}
enableReinitialize
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={props.handleSubmit}
>
It's possible to provide a initial value for validation in the "initialIsValid" prop.
const validationSchema= Yup.object()
const initialValues = { ... }
const initialIsValid = schema.isValidSync(initialValues)
return <Formik
initialValues={initialValues}
validationSchema={validationSchema}
initialIsValid={initialIsValid }
...
>
...
</Formik>
The only solution I found is to explicitly add initialErrors={{..}} to Formik.
In the below example, it's added depending on some condition. Unfortunately that duplicates the Yup validation/message which I also have in the schema. Nothing else worked, no validateOnMount or anything else.
<Formik
enableReinitialize
validationSchema={schema}
onSubmit={ (values) => {
submitForm(values);
}}
initialValues={initialFormValues}
/* Unfortunately a duplication of Yup Schema validation on this field,
but can't force Formik/Yup to validate initially */
initialErrors={!isEmptyObject(initialFormValues) &&
initialFormValues.inactiveApproverCondition &&
{'approverId': 'Selected Approver is no longer eligible. Please choose a different Approver to continue.'}}
>
You should try updating your code follow this
render={({ errors, touched, setFieldValue, isValid, ...rest })
and
<button type="submit" className="btn btn-success" disabled={!isValid}> Kaydet</button>
I'm unable to get handleChange to update an input with dots "." in the name. Has anyone solved this?
<Formik component={({
handleSubmit,
handleChange,
handleBlur,
values,
errors,
}) => (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleChange}
onBlur={handleBlur}
value={values['name.of.input']}
name="name.of.input"
/>
{errors['name.of.input'] && <div>{errors['name.of.input']}</div>}
<button type="submit">Submit</button>
</form>
)} />;
Edit: Here is the refactored version that works
<Formik component={({
initialValues={{
name: {
of: {
input: ''
}
}
}},
handleSubmit,
handleChange,
handleBlur,
values,
errors,
}) => (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleChange}
onBlur={handleBlur}
value={values.name.of.input}
name="name.of.input"
/>
{getIn(errors, 'name.of.input') && <div>getIn(errors, 'name.of.input')</div>}
<button type="submit">Submit</button>
</form>
)} />;
You should use getIn and you can see an examples in the docs here and here.
const inputValue = getIn(values, 'name.of.input')
const inputError = getIn(errors, 'name.of.input')
const inputTouched = getIn(touched, 'name.of.input')
name.of.input means your Formik state should have shape something like this:
{
name: {
of: {
input: ''
}
}
}
Now the values you're getting from Formik will also have the same shape, so to access value off of values you need do this:
values={values.name.of.input}