I want to implement a check form for validating validity in the food ordering project using formik, but I encountered the problem of creating two buttons. No matter which button is clicked, handleSubmit will be called. How can I solve this problem?
The function goBack just sets the status to false.
export default function Checkout(props) { function handleSubmit(event) { // event.preventDefault(); console.log("Hello"); } return ( <Formik initialValues={{ userName: "Hi", street: "", postalCode: "", city: "" }} onSubmit={handleSubmit} > {(props) => ( <Form className={styles["form"]}> <div className={styles["form-control"]}> <div className={styles["form-control__input"]}> <label htmlFor="userName">Your name</label> <Field type="text" name="userName" id="userName"></Field> </div> <div className={styles["form-control__input"]}> <label htmlFor="street">Street</label> <Field type="text" name="street" id="street"></Field> </div> <div className={styles["form-control__input"]}> <label htmlFor="postalCode">Postal code</label> <Field type="text" name="postalCode" id="postalCode"></Field> </div> <div className={styles["form-control__input"]}> <label htmlFor="city">City</label> <Field type="text" name="city" id="city"></Field> </div> </div> <div className={styles["form-actions"]}> <CloseButton type="button" onClick={props.goBack}>Back</CloseButton> <OrderButton type="submit">Confirm</OrderButton> </div> </Form> )} </Formik> ); }
export default function CloseButton(props) { return <button type={props.type} onClick={props.onClick} className={styles["close-button"]}>{props.children}</button>; }
export default function OrderButton(props) { return <button type={props.type} onClick={props.onClick} className={styles['order-button']}>{props.children}</button> }
I want the CloseButton to close the form and return to the order list, but it only calls the handleSubmit created by the Formik component, not the function in the props. I read the documentation but nothing is mentioned about creating a formik with two buttons and is relevant to my question.
Looks like in
props.goBack
you want to reference the component'sprops
, but you are actually using Formik's internalprops
(because it is the most recentprops
declaration). SincegoBack
is not defined on Formik's props, you are passingundefined
as theonClick
handler to the button.The most direct way to solve this problem is to rename one of the props variables. I recommend naming Formik's props
formikProps
or something similar.In my opinion, a better approach is to destructure the props (in both cases, although only one is necessary), like this: