i build a form with Ant design,there is a datepicker input and i need to select
date in a specific date format but when i press submit the date send without any
format. how can i get the date on format after submit the form data
import { Button, Form, Input, DatePicker } from 'antd';
const App = () => {
const onFinish = (value) => {
console.log(value);
};
return (
<Form name="form_item_path" layout="vertical" onFinish={onFinish}>
<Form.Item name="firstName" label="First Name">
<Input />
</Form.Item>
<Form.Item name="start-date">
<DatePicker className='input w-full' format="YYYY-MM-DD HH:mm:ss"/>
</Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form>
);
};
export default App;
Check the following example
you need to convert it to required format using
startdate: value["start-date"].format("YYYY-MM-DD HH:mm:ss")
App.jsx
import { Button, Form, Input, DatePicker } from "antd";
import "./index.css";
import "antd/dist/antd.css";
const App = () => {
const onFinish = (value) => {
let user = {
firstname: value.firstName,
startdate: value["start-date"].format("YYYY-MM-DD HH:mm:ss") //Add your required date format here
};
console.log("Date in proper format", user);
};
return (
<Form name="form_item_path" layout="vertical" onFinish={onFinish}>
<Form.Item name="firstName" label="First Name">
<Input />
</Form.Item>
<Form.Item name="start-date">
<DatePicker className="input w-full" format="YYYY-MM-DD HH:mm:ss" />
</Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form>
);
};
export default App;
Output:
Related
The form campaignid input value is automatically filled in when the page is loaded. When I click on the other fields, it reset to default.
What can I do to prevent default and preserve my campaignid input value?
I'm using a third party script to get URL parameters and insert them into campaignid value.
import { Button, FormControl, Input } from "#chakra-ui/react";
import { Field, Form, Formik } from "formik";
import Script from "next/script";
export default function FormikExample() {
return (
<>
<Script src="https://cdn.jsdelivr.net/gh/gkogan/sup-save-url-parameters/sup.min.js" />
<Formik
initialValues={{
name: "",
}}
onSubmit={(values) => {
setTimeout(() => {
fetch(`https://hooks.zapier.com/hooks/catch/3660927/bte5w77/`, {
method: "POST",
body: JSON.stringify(values, null, 2),
}),
3000;
});
}}
>
{(props) => (
<Form id="hero">
<Field name="name">
<FormControl>
{({ field }) => <Input {...field} type="text" id="name" />}
</FormControl>
</Field>
<Field name="email">
<FormControl>
{({ field }) => <Input {...field} type="email" id="email" />}
</FormControl>
</Field>
<Field name="campaignid">
{({ field }) => (
<FormControl isReadOnly>
<Input {...field} type="hidden" value="" id="campaignid" />
</FormControl>
)}
</Field>
<Button id="submited" isLoading={props.isSubmitting} type="submit">
Submit
</Button>
</Form>
)}
</Formik>
</>
);
}
You need to prevent the default of the submit form.
Use prevent default on your submit function, it will stop that behaviour. More info: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
e.preventDefault()
This is my code without material UI button:
const {register, handleSubmit} = useForm();
const onSubmit = (data) => {
console.log(data)
}
const handleChange = (e) => {
console.log(e.target.files)
}
...
<form id="myFile" onSubmit={handleSubmit(onSubmit)}>
<input id="file1" type="file" {...register("file1")} onChange={handleChange}/>
<input type="submit"/>
</form>
This works for me, but when I try to add material UI button instead of input, I get onChange value but when I click submit. I don't get any form data.
const {register, handleSubmit} = useForm();
const onSubmit = (data) => {
console.log(data)
}
const handleChange = (e) => {
console.log(e.target.files)
}
...
<form id="myFile" onSubmit={handleSubmit(onSubmit)}>
<input id="file1" type="file" {...register("file1")} onChange={handleChange}
style={{display:"none"}}/>
<label htmlFor="file1">
<Button variant="contained" component="span">
Choose file
</Button>
</label>
<input type="submit"/>
</form>
Is there any solution here?
You are forget to mention the type of the button
for Default material ui button type is
type="button"
Check this git Document
you should mention
type="submit"
So do like this
<Button type="submit" variant="contained" component="span">
Choose file
</Button>
You can try something like this:
import React, { useState } from 'react';
import { Button, TextField } from '#material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';
const Form: React.FC = () => {
const schema = object().shape({
username: string().required('username required'),
password: string().required('password required'),
});
const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
const onSubmit = (data: any) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="username"
error={!!errors.username}
label="Username"
helperText={errors.username ? errors.username.message : ''}
type="email"
inputRef={register}
fullWidth
/>
<TextField
name="password"
error={!!errors.password}
label="Password"
inputRef={register}
helperText={errors.password ? errors.password.message : ''}
type="password"
fullWidth
/>
<Button
color="secondary"
type="submit"
variant="contained"
fullWidth
>
Submit
</Button>
</form>
);
};
ref: How to use react-hook-form with ant design or material UI
Currently your submit event is controlled by the whole form element <form onSubmit={handleSubmit(onSubmit)}> but this is possible only when the form has a relevant submit button like <input type="submit"/> but when you use materail ui, MUI button doesnt distincts submit type even if mentioned.
So the solution is to move your onSubmit function at form to down the onClick event of your new MUI button.
The code that works is:
<Button onClick={handleSubmit(onSubmit)} type="submit" variant="contained" component="span"> Submit </Button>
return (
{jobstate.jobs.map((data,i) =>{
<form>
<input type="text" placeholder="Post a comment" onChange={(e) => jobcmthandler(e,data._id,i) } />
<button type="button" onClick={postcmt} >Send</button>
</form>
})}
)
I generate dynamic HTML using the map function and I want to disabled button if text null for induvial form and also how to get text value on button click in react js
I can't really see why you'd want to do this but here you go (example):
import React, { useState } from "react";
export default function App() {
return ["Name", "Age"].map((label) => <Form label={label} />);
}
function Form({ label }) {
const [readValue, writeValue] = useState("");
return (
<form>
<label>{label}</label>
<input
type="text"
placeholder="Post a comment"
onChange={(e) => writeValue(e.target.value)}
value={readValue}
/>
<button
type="button"
onClick={() => console.log("Submit")}
disabled={readValue === ""}
>
Send
</button>
</form>
);
}
Form.js Code here
import React , {Component} from 'react';
import { Form, Input, Button } from 'antd';
import axios from 'axios';
class CustomForm extends Component {
handFormSubmit2 = (event) => {
event.preventDefault()
const name = event.target.elements.name.value;
const comment = event.target.elements.comment.value;
console.log(name , comment)
}
render(){
return (
<>
<Form onSubmit={this.handFormSubmit2}>
<Form.Item label="Name">
<Input name='name' placeholder="Enter name here" />
</Form.Item>
<Form.Item label="Comment">
<Input name="comment" placeholder="Comment here" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
</>
);
}
}
export default CustomForm;
The problem i am facing is the button is not working even if i remove the event.preventDefault() it stills not submit and refresh the page
Your are using antd
Read the form documentation , you should use their onFinish callback instead of onSubmit
<Form onFinish={this.handFormSubmit2}>
<Form.Item label="Name">
<Input name='name' placeholder="Enter name here" />
</Form.Item>
<Form.Item label="Comment">
<Input name="comment" placeholder="Comment here" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
here your full example working with antd
import React , {Component} from 'react';
import { Form, Input, Button } from 'antd';
import axios from 'axios';
class CustomForm extends Component {
handFormSubmit2 = (values) => {
console.log(values.name , values.comment)
}
render(){
return (
<>
<Form onFinish={this.handFormSubmit2}>
<Form.Item label="Name" name='name'>
<Input placeholder="Enter name here" />
</Form.Item>
<Form.Item label="Comment" name="comment">
<Input placeholder="Comment here" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
</>
);
}
}
export default CustomForm;
working example
I have a very simple formik setup where I need to pass the new initial values when users press reset form button. I am following doc but I end up creating recursive issue.
formReset() is passed to formik as a param of onReset. The function is called but I am not sure where is the recursion happening.
Here is a codesandbox for your convenient. Change form value then try to reset the form.
App.js
// Helper styles for demo
import "./helper.css";
import { MoreResources, DisplayFormikState } from "./helper";
import React from "react";
import { render } from "react-dom";
import { Formik } from "formik";
import * as Yup from "yup";
const formReset = (_, {resetForm}) => {
resetForm({email: ''});
}
const App = () => (
<div className="app">
<h1>
Basic{" "}
<a
href="https://github.com/jaredpalmer/formik"
target="_blank"
rel="noopener noreferrer"
>
Formik
</a>{" "}
Demo
</h1>
<Formik
initialValues={{ email: "populate#test.com" }}
onSubmit={async values => {
await new Promise(resolve => setTimeout(resolve, 500));
alert(JSON.stringify(values, null, 2));
}}
onReset={formReset}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required")
})}
>
{props => {
const {
values,
touched,
errors,
dirty,
isSubmitting,
handleChange,
handleBlur,
handleSubmit,
handleReset
} = props;
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email" style={{ display: "block" }}>
Email
</label>
<input
id="email"
placeholder="Enter your email"
type="text"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={
errors.email && touched.email
? "text-input error"
: "text-input"
}
/>
{errors.email && touched.email && (
<div className="input-feedback">{errors.email}</div>
)}
<button
type="button"
className="outline"
onClick={handleReset}
disabled={!dirty || isSubmitting}
>
Reset
</button>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
<DisplayFormikState {...props} />
</form>
);
}}
</Formik>
<MoreResources />
</div>
);
render(<App />, document.getElementById("root"));
Edit:
So... a better option would be to use initialValues in useState and pass enableReinitialize and change the state to "reset" the form. It's more easy than trying to use resetForm.
You don't need to pass a function to onReset and call resetForm, you can do that by just pass the type reset to the button and have the Form component instead of normal html form tag.
The Form component will handle the handleReset that will be trigger when you have a button with type="reset".
<Form>
{/* other components */}
<button
type="reset"
className="outline"
disabled={!dirty || isSubmitting}
>
Reset
</button>
</Form>
Here is a working example.