js with event Button not wroking - javascript

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

Related

how to get antd datePicker value in format after submission

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:

The Student's List Won't Added Using React JS Ant Design

It supposed to add the student list when I click on the button, but it doesn't.
It should be like the pict below:
I already check my code, and here it is:
import React from "react";
import './App.css';
import "antd/dist/antd.css";
import { Form, Input, Button } from "antd";
import Operation from "antd/lib/transfer/operation";
import { PlusCircleOutlined } from '#ant-design/icons';
function App() {
return (
<div className="App">
<h2>Dynamic Form Dengan Validasi</h2>
<form>
<Form.Item name={"teacher"} label="Teacher Name">
<Input placeholder="Teacher Name"></Input>
</Form.Item>
<Form.Item name={"class"} label="Class Name">
<Input placeholder="Class"></Input>
</Form.Item>
<Form.List name={"students"}>
{(fields, {add, remove}) => (
<>
{fields.map((field, index)=>{
return (
<Form.Item name={[field.name,"first"]} label={`${index + 1}-Student`}>
<Input placeholder="First Name"></Input>
</Form.Item>
);
})}
<Form.Item>
<Button icon={<PlusCircleOutlined />} type="dashed" block onClick={() => { add();}}>
Add A Student</Button>
</Form.Item>
</>
)}
</Form.List>
</form>
</div>
);
}
export default App;
I don't know what went wrong, only see the warning in the first pict.
You're missing Form.Provider. You need it in order to use Form
import { FormProvider } from 'react-hook-form';
After that make sure to wrap your <Form> tag with a <FormProvider> tag.
function App() {
return (
<div className="App">
<h2>Dynamic Form Dengan Validasi</h2>
<FormProvider>
<Form>
<Form.Item name={"teacher"} label="Teacher Name">
<Input placeholder="Teacher Name"></Input>
</Form.Item>
<Form.Item name={"class"} label="Class Name">
<Input placeholder="Class"></Input>
</Form.Item>
<Form.List name={"students"}>
{(fields, {add, remove}) => (
<>
{fields.map((field, index)=>{
return (
<Form.Item name={[field.name,"first"]} label={`${index + 1}-Student`}>
<Input placeholder="First Name"></Input>
</Form.Item>
);
})}
<Form.Item>
<Button icon={<PlusCircleOutlined />} type="dashed" block onClick={() => { add();}}>
Add A Student
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form>
</FormProvider>
</div>
);
}

How to prevent a form input value from disappearing on click in other fields?

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()

Redirect to Component onSubmit

My react app is not redirecting to the dashboard page after submitting a form. I tried using react-router-dom Redirect function but still with no success. I then opt-in for Browser History. push but still no success.
for the latter trial, the URL changes to /dashboard but the component remains on the form page, it doesn't move to dashboard until I reload the page
form field
<form>
<Input
displayValidationErrors={displayValidationErrors("fullname", validators)}
name="fullname"
type="text"
label="Full Name"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("password", validators)}
name="password"
type="password"
label="Password"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("password2", validators)}
name="password2"
type="password"
label="Confirm Password"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("email", validators)}
name="email"
type="email"
label="Email Address"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors(
"phone_number",
validators
)}
name="phone_number"
type="number"
label="Phone Number"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("card_number", validators)}
value={data.card_number}
name="card_number"
type="text"
label="Card Number"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("date", validators)}
value={data.date}
name="date"
type="text"
label="Expiry Date"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("pin", validators)}
name="pin"
type="password"
label="PIN"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<div className="col-lg-12 loginbttm">
<div className=" login-btm login-button">
<Button
handleClick={onSubmit}
type="submit"
className="btn btn-primary"
label="SUBMIT"
disabled={!isFormValid(validators)}
/>
</div>
</div>
</form>;
onSubmit function
const onSubmit = (e) => {
e.preventDefault();
browserHistory.push("/dashboard");
};
Button Component
const Button = ({ type, className, handleClick, label, disabled }) => (
<button
type={type}
className={className}
onClick={handleClick}
disabled={disabled}
>
{label}
</button>
);
My app.js
function App() {
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/dashboard">
<Dashboard />
</Route>
<Route exact path="/">
<Form />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
I don't see createBrowserHistory or something like <Router history={history}> so I guess you are using the default browser history. In that case you need withRouter to make it work:
import React from "react";
import { withRouter } from "react-router-dom";
function App() {
const onSubmit = (e) => {
e.preventDefault()
this.props.history.push("/personalInfo");
}
...
}
export default withRouter(App);
More about withRouter solution here
More about createBrowserHistory solution here
For functional component with react-router V5, you can also do with hooks:
import { useHistory } from "react-router-dom";
function App() {
let history = useHistory();
const onSubmit = (e) => {
e.preventDefault()
history.push('/dashboard');
}
return (
<Router>
<div className="App">
...
</div>
</Router>
);
}
Take a look at this to know more about useHistory
try using below. hope it'll help
this.props.history.push({
pathname: '/dashboard'
})
Another way of doing it with the function component -
import {withRouter} from "react-router-dom";
function SignIn({history}) {
const submit = (event) => {
event.preventDefault();
history.push("/profile");
}
....
}
export default withRouter(SignIn)

Handle submit and change from child component in react

I have two components :
LoginForm which is used to render the form to login in the app
LoginPage which get the data entered in the LoginForm component and send it to a server
For the moment I would like to handle the form submit and the change of an input value. I read these two articles in the react official website to help me :
https://reactjs.org/docs/lifting-state-up.html
https://reactjs.org/docs/forms.html
But I still don't detect the submit and the change from the LoginPage component when I'm entering a value in LoginForm.
Can you help me to see where is my mistake ?
Thanks by advance.
My two components :
LoginPage.js
class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
login: true, //switch between Login and SignUp
email: '',
password: '',
firstName: '',
lastName: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleSubmit(){
alert("SUBMIT");
}
handleInputChange(event) {
alert("YOUHOU");
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
alert("YEEEP");
}
render(){
return (
<div>
<div>
{this.state.login ?
<Login onSubmit={this.handleSubmit} onChange={this.handleInputChange}/>
:
<Register />
}
</div>
<a
onClick={() => this.setState({ login: !this.state.login })}
>
{this.state.login ? 'Besoin d\'un compte ?' : 'Déjà un compte ?'}
</a>
</div>
)
}
}
LoginForm.js
class LoginForm extends Component {
render(){
return (
<div>
<Card>
<form onSubmit={this.props.handleSubmit}>
<div>
<div>
<TextField name="email" floatingLabelText="Email" errorText="Champ obligatoire" type="text" onChange={this.props.handleInputChange}/>
</div>
<div>
<TextField name="password" floatingLabelText="Mot de passe" errorText="Champ obligatoire" type="password" onChange={this.props.handleInputChange} />
</div>
<CardActions>
<div>
<RaisedButton label="Se connecter" primary={true} type="submit" fullWidth />
</div>
</CardActions>
</div>
</form>
</Card>
</div>
);
}
}
handleInputChange is passed down to LoginForm as onChange prop and similarly handleSubmit is passed down by the name onSubmit and hence you need to use it like
class LoginForm extends Component {
render(){
return (
<div>
<Card>
<form onSubmit={this.props.onSubmit}>
<div>
<div>
<TextField name="email" floatingLabelText="Email" errorText="Champ obligatoire" type="text" onChange={this.props.onChange}/>
</div>
<div>
<TextField name="password" floatingLabelText="Mot de passe" errorText="Champ obligatoire" type="password" onChange={this.props.onChange} />
</div>
<CardActions>
<div>
<RaisedButton label="Se connecter" primary={true} type="submit" fullWidth />
</div>
</CardActions>
</div>
</form>
</Card>
</div>
);
}
}

Categories