when I click on the submit button on react js, Submit doesn't work, I don't know why?
I'm using ant.design Ui component in on backend Using Django python.
import React from "react";
import { Form, Input, Button } from "antd";
const FormItem = Form.Item;
class ExtrashiftForm extends React.Component {
handleFormSubmit = (event) => {
event.preventDefault();
const title = event.target.elements.title.value;
const manager = event.target.elements.manager.value;
const gender = event.target.elements.gender.value;
const Lable = event.target.elements.Lable.value;
const datetime = event.target.elements.datetime.value;
console.log(title, manager,gender,Lable,datetime);
};
render() {
return (
<div>
<Form onSubmit={this.handleFormSubmit}>
<FormItem name="title" label="Title">
<Input placeholder="title here" />
</FormItem>
<FormItem name="manager" label="Manager">
<Input placeholder="select Manager Name .. " />
</FormItem>
<FormItem name="gender" label="Gender">
<Input placeholder="select Gender Type .. " />
</FormItem>
<FormItem name="Lable" label="Lable">
<Input />
</FormItem>
<FormItem name="datetime" label="DateTime">
<Input />
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">
Ok
</Button>
</FormItem>
</Form>
</div>
);
}
}
export default ExtrashiftForm;
this part of code included inside the layout page, and all text coming but when I check Console in chrome browser, didn't send any data to console.
please help me, thank you
Change onSubmit to onFinish.
onFinish cb will have values as object. That also need to update.
<Form onFinish={(values) => console.log(values)}>
or
<Form onFinish={({title, manager,gender,Lable,datetime}) => console.log({title, manager,gender,Lable,datetime})}>
Try this one
<Form onFinish={(values) => this.handleFormSubmit(values)}>
<FormItem label="Title">
<Input placeholder="title here" name="title" />
</FormItem>
</Form>
const handleFormSubmit = (values) => {
const title = values.title;
console.log(title);
};
Related
I created a login form and now I want to convert my input fields to re- usable component. I created separate common input.jsx file. This is input.jsx file's code.
import React from "react";
const Input = ({ name, label, value, onChange }) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input
value={value}
onChange={onChange}
id={name}
name={name}
type="text"
className="form-control"
/>
</div>
);
};
export default Input;
and imported it to my loginForm.jsx. Here is my loginForm.jsx render method
handleChange = ({ currentTarget: input }) => {
const account = { ...this.state.account };
account[input.name] = input.value;
this.setState({ account });
};
render() {
const { account } = this.state;
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
<Input
name="password"
value={account.password}
label="Password"
onChange={this.handleChange}
/>
<button className="btn btn-primary">Login</button>
</form>
</div>
);
}
But after adding below code to my loginForm.jsx,
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
code and deleted previous code ,
<div className="form-group">
<label htmlFor="username">Username</label>
<input
value={account.username}
name="username"
onChange={this.handleChange}
ref={this.username}
id="username"
type="text"
className="form-control"
/>
</div>
suddenly my login page not loading.(Empty page).
My login page's console showing below error.
The above error occurred in the <LoginForm> component:
at LoginForm (http://localhost:3000/main.5d4e82bfe117bc198b43.hot-update.js:27:5)
at Route (http://localhost:3000/static/js/bundle.js:54444:5)
at Switch (http://localhost:3000/static/js/bundle.js:54739:5)
at main
at App
at Router (http://localhost:3000/static/js/bundle.js:54612:5)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:53870:5)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
How can I define input attributes in typescript? I have an AddUser Component and TextInput Component, I want to import the TextInput component inside the AddUser component and then pass props to the TextInput component.
AddUser.tsx
import Button from '../Shared/Form/Button/Button';
import Form from '../Shared/Form/Form';
import TextArea from '../Shared/Form/TextArea/TextArea';
import TextInput from '../Shared/Form/TextInput/TextInput';
const AddUser = () => {
return (
<div>
<h1>Add User</h1>
<Form method="post" className={'user-form'}>
<TextInput label={'Name'} type="text" name="name" required />
<TextInput label={'Email'} type="email" name="email" required />
<TextInput label={'Country'} type="text" name="country" required />
<TextInput label={'Phone'} type="text" name="phone" required />
<TextArea label={'Address'} name="address" cols="30" rows="4" />
<div className="form-button">
<Button type={'submit'} className={'btn-add'}>
Add
</Button>
<Button type={'submit'} className={'btn-close'}>
Cancel
</Button>
</div>
</Form>
</div>
);
};
export default AddUser;
TextInput.tsx
const TextInput = ({ className, label, ...rest }: { className: string; label: string }) => {
return (
<div className={`${className} form-field`}>
<label htmlFor={label}>{label}</label>
<input {...rest} />
</div>
);
};
export default TextInput;
You can extend HTMLProps which comes with react:
import { HTMLProps } from "react";
interface MyCOmponentProps extends HTMLProps<HTMLInputElement> {
{...}
}
This is how we can make a reusable component. maybe I missed something in onChangeAction according to type script. please let me know me in the comment section so that i can help you better
Example codesandbox
const AddUser = () => {
return (
<div>
<h1>Add User</h1>
<form method="post" className={"user-form"}>
<TextInput
label={"Name"}
placeholder="Name"
type="text"
name="name"
required
/>
<TextInput
label={"Email"}
placeholder="Email"
type="email"
name="email"
required
/>
<TextInput
label={"Country"}
placeholder="Country"
type="text"
name="country"
required
/>
<TextInput
label={"Phone"}
placeholder="Phone"
type="text"
name="phone"
required
/>
</form>
</div>
);
};
export default AddUser;
const TextInput = ({
className,
label,
value,
type,
onChangeAction,
placeholder
}) => {
return (
<div className={`${className} form-field`}>
<label htmlFor={label}>{label}</label>
<input
placeholder={placeholder || "Text"}
type={type || "text"}
value={value}
onChange={onChangeAction}
/>
</div>
);
};
I hope you will be able to help me with an answer to my question. I am using react-modal and inside the modal I have an input where users can write an email. When writing the email it should update the state but that is not happening.
What is happening right now is that the model re-renders every time I write a new letter and that results in the state only updating with the first letter I typed and then focus is lost.
I am using react hooks. I know that changes a bit.
My code looks like the following:
import React, { useState, useContext } from 'react';
import AppContext from '../../AppContext.jsx';
import GroupContext from './GroupContext.jsx';
import Section from '../../Elements/PageContent/Section.jsx';
import PageTitle from '../../Elements/PageContent/PageTitle.jsx';
import WhiteContainer from '../../Elements/PageContent/WhiteContainer.jsx';
import { Form, FormGroup, FormSection, FormSection_Split, Label, Input, Select, Submit } from '../../Elements/Forms/FormCollection.jsx';
import { MusicGenres } from '../../Elements/Forms/MusicGenres.jsx';
import { Years } from '../../Elements/Forms/Years.jsx';
import { H3 } from '../../Elements/Fonts/FontCollection.jsx';
import { Icon } from '../../Elements/Image/ImageUtil.jsx';
import ReactModal from "react-modal";
import { useModal } from "react-modal-hook";
export default function Groups(props) {
const AC = useContext(AppContext);
const GC = useContext(GroupContext);
const [groupName, setGroupName] = useState("");
const [groupDescription, setGroupDescription] = useState("");
const [memberEmail, setMemberEmail] = useState("");
const [groupMembers, setGroupMembers] = useState([]);
const [showModal, hideModal] = useModal(() => (
<ReactModal className="DialogPopup" isOpen ariaHideApp={false}>
<Form>
<FormGroup>
<FormSection>
<Label htmlFor="memberEmail" title="Email of your group member:" />
<Input type="email" name="memberEmail" value={memberEmail} onChange={(e) => setMemberEmail(e.target.value)} placeholder="#" />
</FormSection>
</FormGroup>
</Form>
<button onClick={(e) => hideModal()} className="Close" aria-label="Close popup"><Icon iconClass="fal fa-times" /></button>
</ReactModal>
), []);
async function addObjectToGroupMembersArray(e) {
e.preventDefault();
console.log("Adding member");
}
return (
<React.Fragment>
<PageTitle title="Add group" />
<Section>
<Form>
<FormGroup>
<FormSection>
<WhiteContainer>
<Label htmlFor="groupName" title="Group name:" />
<Input type="text" name="groupName" value={groupName} onChange={(e) => setGroupName(e.target.value)} maxLength="60" required />
<span className="CharactersLeft">Characters left: {60 - groupName.length}</span>
</WhiteContainer>
</FormSection>
<FormSection>
<WhiteContainer>
<Label htmlFor="groupDescription" title="Describe your group:" />
<textarea name="groupDescription" id="groupDescription" value={groupDescription} onChange={(e) => setGroupDescription(e.target.value)} maxLength="500"></textarea>
<span className="CharactersLeft">Characters left: {500 - groupDescription.length}</span>
</WhiteContainer>
</FormSection>
<FormSection>
<WhiteContainer>
<Label htmlFor="groupMembers" title="List the emails of your group members?" />
<a href="#" className="AddLink" aria-label="Add member" title="Click to add a member" onClick={(e) => { e.preventDefault(); showModal(); }}>
<Icon iconClass="fal fa-plus" />
</a>
</WhiteContainer>
</FormSection>
<FormSection className="FormSection--Submit">
<Submit text="Create group" />
</FormSection>
</FormGroup>
</Form>
</Section>
</React.Fragment>
);
}
Does anyone of you know why the modal is updating every time I type, resulting in not being able to write anything in the input. Should i use "ref" and if I should, how would I do that?
The onChange method I am using is always working, just not inside react-modal.
I finally figured it out. It's because modal is working a little like the useEffect hook. If i add memberEmail to the bottom of the modal state, then it is working.
const [memberEmail, setMemberEmail] = useState("");
const [showModal, hideModal] = useModal(() => (
<ReactModal className="DialogPopup" isOpen ariaHideApp={false}>
<Form>
<FormGroup>
<FormSection>
<Label htmlFor="memberEmail" title="Email of your group member:" />
<Input type="email" name="memberEmail" value={memberEmail} onChange={(e) => setMemberEmail(e.target.value)} placeholder="#" />
</FormSection>
</FormGroup>
</Form>
<button onClick={(e) => hideModal()} className="Close" aria-label="Close popup"><Icon iconClass="fal fa-times" /></button>
</ReactModal>
), [memberEmail]);
What about creating an external function that you would call in onChange?
something like:
const handleOnChange = (event) => {
setMemberEmail(event.target.value);
}
// then call it in your component
<Input type="email" name="memberEmail" value={memberEmail} onChange={handleOnChange} placeholder="#" />
Whats wrong with this Form , when i click submit button the signInSubmitHandler() function is not called , i tested it with a simple Button with onClick and it works but if i use Form with submit button it doesnt work. (im using reactjs)
in SignInForm.jsx file:
const SignInForm = (props) => {
return (
<React.Fragment>
<h1>Welcome to ToDo</h1>
<form onSubmit={props.signInSubmitHandler} className={style.signInForm}>
<div className={style.signInFormImportantElements}>
<span className={style.userFormsErrors}>{props.userEmailError}</span>
<input
name="userEmail"
type="email"
placeholder="email"
value={props.currentUserEmailText}
className={style.signInText}
onChange={(e) => {
props.signInOnChangeHandler(e);
}}
onBlur={(e) => props.signInOnBlurHandler(e)}
/>
<span className={style.userFormsErrors}>{props.userPasswordError}</span>
<input
name="userPassword"
type="password"
placeholder="password"
value={props.currentUserPasswordText}
className={style.signInText}
onChange={(e) => {
props.signInOnChangeHandler(e);
}}
onBlur={(e) => props.signInOnBlurHandler(e)}
/>
<input type="submit" value="Submit" className={style.signInSubmit} />
</div>
<div className={style.signInLinks}>
Forget Password
Create Account
</div>
</form>
</React.Fragment>
);
};
in app.jsx file :
signInSubmitHandler() {
console.log('waaaat');
}
Form Code image
props
signInSubmitHandler binding
signInSubmitHandler function
your function has one param
signInSubmitHandler(e) {
console.log('waaaat');
}
so try this
<form onSubmit={(e) => props.signInSubmitHandler(e)} className={style.signInForm}>
I'm a beginner in React and I was following a tutorial on how to create a React app with Django backend.In the video he uses Ant Design Components v3(that was the latest when the video was made). Now I'm using the latest one v4 and they changed the form onSubmit to onFinish. After some research in the comments, people posted about the update and how to make it work but no luck.The problem is that I'm trying to get the data from the form inputs(title and content) and it shows undefined.Any ideas?
Here is the component:
import React, { Component } from "react";
import { Form, Input, Button } from "antd";
const FormItem = Form.Item;
class CustomForm extends Component {
handleFormSubmit = (values) => {
const title = values.title;
const content = values.content;
console.log(title, content, values);
};
render() {
return (
<div>
<Form onFinish={(values) => this.handleFormSubmit(values)}>
<FormItem label="Title">
<Input name="title" placeholder="Article Content" />
</FormItem>
<FormItem label="Content">
<Input
name="content"
placeholder="Enter Article Content"
/>
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">
Submit
</Button>
</FormItem>
</Form>
</div>
);
}
}
export default CustomForm;
And the output of the console.log() is:
undefined, undefined, {}
It's because Form.Item or, in your case, FormItem, must have a name prop which is missing so values are not being saved against that key, so e.g.
Change this:
<FormItem label="Title">
<Input name="title" placeholder="Article Content" />
</FormItem>
To
<FormItem label="Title" name="title">
<Input placeholder="Article Content" />
</FormItem>
Here is what i use instead of onSubmit for antd 4.x.x Form:
import React from 'react';
import { Form, Input, Button } from 'antd';
const FormItem = Form.Item;
class CustomForm extends React.Component {
handleFormSubmit = (values) => {
const title = values.title;
const content = values.content;
console.log(title, content);
};
render(){
return (
<div>
<Form onFinish={(values) => this.handleFormSubmit(values)}>
<FormItem label="Title" name="title">
<Input placeholder="Put a title here" />
</FormItem>
<FormItem label="Content" name="content">
<Input placeholder="Enter some content ..." />
</FormItem>
<FormItem >
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
);
}
}
export default CustomForm;