I ve got a form consisits of two inputs (emain, password) and one checkbox. Code is here:
<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Email adress"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign in
</Button>
</Box>
To get the values of Email and Password I use smth.like:
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
console.log({
email: data.get('email'),
password: data.get('password'),
});
};
But what's the best practice to get the value of checkbox "Remember me" (in FormControlLabel)? Of course, I can make a new function to handle the changes of checkbox like:
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
onChanges = {newFunction}
label="Remember me"
/>
But I think that's it's not a good idea, because I don't need to get all the changes of this checkbox, I just need to know the value of this checkbox in the moment of submitting the form.
As you pointed out, you can make the checkbox controlled with a React state, but it's not needed if you are inside a form, since the form owns the info of each input element inside of it, but in order to do that you must set a name attribute on each input element, then you can read the values by instantiating a FormData:
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const data = formData.entries();
for (const entry of data) console.log(entry);
};
A working example here: https://stackblitz.com/edit/react-ictfjr
You should use Usestate hooks
Handling a multiple CheckBox : Link
import React, {useState} from 'react'
export default () => {
const [fName, setfName] = useState('');
const [lName, setlName] = useState('');
const [phone, setPhone] = useState('');
const [email, setEmail] = useState('');
const [isChecked, setIsChecked] = useState(false);
const handleOnChange = () => {
setIsChecked(!isChecked);
};
const submitValue = () => {
const frmdetails = {
'First Name' : fName,
'Last Name' : lName,
'Phone' : phone,
'Email' : email
}
console.log(frmdetails);
}
return(
<>
<hr/>
<div className="topping">
<input
type="checkbox"
id="topping"
name="topping"
value="Paneer"
checked={isChecked}
onChange={handleOnChange}
/>
Paneer
</div>
<input type="text" placeholder="First Name" onChange={e => setfName(e.target.value)} />
<input type="text" placeholder="Last Name" onChange={e => setlName(e.target.value)} />
<input type="text" placeholder="Phone" onChange={e => setPhone(e.target.value)} />
<input type="text" placeholder="Email" onChange={e => setEmail(e.target.value)} />
<button onClick={submitValue}>Submit</button>
</>
)
}
Related
I have developed a registration form and I tried using validation format but it is not working. I don't know how and where to code a function for it and apply it. please help me how to do it. I will attach the code i have done till now.
import React, { useState } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate } from 'react-router';
export default function Create() {
let navigate = useNavigate();
const [Employee_name, setEmployee_name] = useState('');
const [Employee_id, setEmployee_id] = useState('');
const [Employee_address, setEmployee_address] = useState('');
const [Employee_post, setEmployee_post] = useState('');
const postData = () => {
axios.post(`http://localhost:5000/qo`, {
Employee_name,
Employee_id,
Employee_address,
Employee_post
}).then(() => {
navigate('/read')
})
alert('Data Saved')
}
return (
<div>
<Form className="create-form">
<Form.Field required={true}>
<label>Employee Name</label>
<input placeholder='Employee Name' onChange={(e) => setEmployee_name(e.target.value)} required={true}/>
</Form.Field>
<Form.Field required={true}>
<label>Employee ID</label>
<input placeholder='Employee ID' onChange={(e) => setEmployee_id(e.target.value)} required={true}/>
</Form.Field>
<Form.Field required={true}>
<label>Employee Address</label>
<input placeholder='Employee Address' onChange={(e) => setEmployee_address(e.target.value)} required={true}/>
</Form.Field>
<Form.Field required={true}>
<label>Employee Position</label>
<input placeholder='Employee Position' onChange={(e) => setEmployee_post(e.target.value)} required={true}/>
</Form.Field>
<Button onClick={postData} type='submit'>Submit</Button>
</Form>
</div>
)
}
There are good libraries out there, that can help you with form validation before allowing a user to submit the form.
One such library could be formik together with Yup.
This is how I do client side form validation on my forms:
Login schema (made with Yup):
import * as Yup from 'yup';
const loginSchema = Yup.object().shape({
username: Yup.string()
.min(3, 'Minimum 3 chars')
.max(50, 'Max 50 chars')
/* password: Yup.string()
.min(6, 'Minimum 6 chars')
.max(50, 'Max 50 chars')
*/
});
Login component:
export const Login = () => {
const [loading, setLoading] = useState(false);
const formik = useFormik({
initialValues: {
username: ''
},
validationSchema: loginSchema,
onSubmit: async (values, {setStatus, setSubmitting}) => {
setLoading(true);
setStatus(null);
try {
// Call your API function to post to the backend here
// You can access your form values in the "values" parameter
setLoading(false);
} catch (error) {
console.error(error);
setStatus('User not found');
setSubmitting(false);
setLoading(false);
}
}
});
}
return (
<form
onSubmit={formik.handleSubmit}
className={'auth-form-wrapper'}
>
{/* begin::Heading */}
<div className={'auth-form-header'}>
<h1>Log in</h1>
<div className={'auth-error-message-container'}>
formik.status && (
<p className={'error-message'}>{formik.status}</p>
)
}
</div>
</div>
{/* end::Heading */}
{/* begin::Form group content */}
<div className={'auth-form-content'}>
{/* begin::Form group */}
<div className={'dynamic-input-container'}>
<input type='text'
id="username"
value={formik.values.username}
onChange={formik.handleChange}
placeholder='Username'
className={'dynamic-input auth-input ' + clsx(
{'is-invalid': formik.touched.username && formik.errors.username},
{
'is-valid': formik.touched.username && !formik.errors.username
}
)}
autoComplete='off'
/>
{formik.touched.username && formik.errors.username && (
<div className='fv-plugins-message-container'>
<span role='alert'>{formik.errors.username}</span>
</div>
)}
</div>
{/* end::Form group*/}
{/* begin::Action */}
<div className='auth-btn-container'>
<Button variant="contained" size="medium" type={'submit'} disabled={loading}>
{
!loading ? <span>Continue</span>
:
(
<span className={'auth-spinner-container'}>
<ClipLoader
loading={loading}
size={20}
aria-label='Loading Spinner'
/>
</span>
)
}
</Button>
</div>
{/* end::Action */}
</div>
{/* end::Form group content */}
</form>
);
Please note, that in my example I only have a "username" input, but you can obviously add as many fields as you wish.
Documentation:
Formik: https://formik.org/docs/tutorial
Yup: https://www.npmjs.com/package/yup
clxs: https://www.npmjs.com/package/clsx
import React, { useState } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate } from 'react-router';
export default function Create() {
let navigate = useNavigate();
const [Employee_name, setEmployee_name] = useState('');
const [Employee_id, setEmployee_id] = useState('');
const [Employee_address, setEmployee_address] = useState('');
const [Employee_post, setEmployee_post] = useState('');
const postData = e => {
e.preventDefault();
if(Employee_name.length == 0) return false;
if(Employee_id.length == 0) return false;
if(Employee_address.length == 0) return false;
if(Employee_post.length == 0) return false;
axios.post(`http://localhost:5000/qo`, {
Employee_name,
Employee_id,
Employee_address,
Employee_post
}).then(() => {
navigate('/read')
})
alert('Data Saved')
}
return (
<div>
<Form className="create-form" onSubmit={e => postData(e)}>
<Form.Field required={true}>
<label>Employee Name</label>
<input placeholder='Employee Name' onChange={(e) => setEmployee_name(e.target.value)} required={true}/>
</Form.Field>
<Form.Field required={true}>
<label>Employee ID</label>
<input placeholder='Employee ID' onChange={(e) => setEmployee_id(e.target.value)} required={true}/>
</Form.Field>
<Form.Field required={true}>
<label>Employee Address</label>
<input placeholder='Employee Address' onChange={(e) => setEmployee_address(e.target.value)} required={true}/>
</Form.Field>
<Form.Field required={true}>
<label>Employee Position</label>
<input placeholder='Employee Position' onChange={(e) => setEmployee_post(e.target.value)} required={true}/>
</Form.Field>
<Button type='submit'>Submit</Button>
</Form>
</div>
)
}
This is updated code from your snippet. try this and let me know what's the progress.
I really appreciate you.
import React,{ useState} from 'react';
import { Button, Checkbox, Form } from 'semantic-ui-react';
import axios from 'axios';
const Create = () => {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [checkbox, setCheckBox] = useState(false);
Here I am sending data to a mock api I created
const postData = () =>{
axios.post(`https://61cb2af8194ffe0017788c01.mockapi.io/fakeData`,{
firstName,
lastName,
checkbox
})
}
This is the method I created to reset the form but it does not work.
const resetForm = () => {
postData();
setFirstName(" ");
setLastName(" ");
setCheckBox(false);
}
This is my form where on click i am calling resetForm function but it is not resetting it
is sending the data but not resetting the form.
return(
<div>
<Form>
<Form.Field>
<label>First Name</label>
<input id="f1" placeholder='First Name' onChange={(e)=>setFirstName(e.target.value) } />
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input id="last1" placeholder='Last Name' onChange={(e)=>setLastName(e.target.value)}/>
</Form.Field>
<Form.Field>
<Checkbox id="c1" label='I agree to the Terms and Conditions' onChange={(e)=>setCheckBox(!checkbox)}/>
</Form.Field>
<Button type='submit' onClick={resetForm}>Submit</Button>
</Form>
<br></br>
<Button onClick={()=>navigate(-1)}>Go Back</Button>
</div>
)
}
export default Create;
Actually it will reset the form, the problem is you do not use Controlled Components to show the latest update value in UI
you should bind the value like this:
<input type="text" value={this.state.value} onChange={this.handleChange} />
You can refer the doc here:
https://reactjs.org/docs/forms.html
You can reset your form using the native form.reset() method.
const Create = () => {
const ref = React.useRef(null);
const resetForm = () => ref.current.reset();
return (
<div>
<Form ref={ref}>
<Form.Field>
<label>First Name</label>
<input id="f1" placeholder="First Name" onChange={(e) => setFirstName(e.target.value)} />
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input id="last1" placeholder="Last Name" onChange={(e) => setLastName(e.target.value)} />
</Form.Field>
<Form.Field>
<Checkbox
id="c1"
label="I agree to the Terms and Conditions"
onChange={(e) => setCheckBox(!checkbox)}
/>
</Form.Field>
<Button type="submit" onClick={resetForm}>
Submit
</Button>
</Form>
<br></br>
<Button onClick={() => navigate(-1)}>Go Back</Button>
</div>
);
};
export default Create;
For that, you have to set value property in your input. Try this
const Create = () => {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [checkbox, setCheckBox] = useState(false);
const postData = () => {
console.log(firstName, lastName, checkbox);
};
const resetForm = () => {
postData();
setFirstName(" ");
setLastName(" ");
setCheckBox(false);
};
return (
<div>
<Form>
<Form.Field>
<label>First Name</label>
<input
id="f1"
placeholder="First Name"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input
id="last1"
placeholder="Last Name"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
</Form.Field>
<Form.Field>
<Checkbox
id="c1"
label="I agree to the Terms and Conditions"
checked={checkbox}
onChange={(e) => setCheckBox(!checkbox)}
/>
</Form.Field>
<Button type="submit" onClick={resetForm}>
Submit
</Button>
</Form>
</div>
);
};
I'm trying to delete my file input field data from e.target but i need the rest of the e.target data to send to emailjs.
The problem is when user uploads a file in my form, the file is most of the time bigger than 50kb and this is the limit for my account on emailjs.
I don't need to send my file to emailjs but i need it to just be stored in my database.
I have tried to clear the form field before sending it to emailjs
with fileUpload.current.value = ""; but the data is still actief in
e.target.
This is e.target Data. i need the data to stay in this way in e.target to send to emailjs
<form class="Grade_inputForm__1lbhQ" autocomplete="off">
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="text" name="name" required="" class="Grade_input__22PTE" placeholder="Name*" maxlength="10">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="email" required="" name="email" class="Grade_input__22PTE" placeholder="Email*">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="text" name="Address" required="" class="Grade_input__22PTE" placeholder="Address*">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="tel" name="phone" class="Grade_input__22PTE" placeholder="Phone">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="file" class="Grade_input__22PTE" name="5349366.jpg">
</div>
<div class="Grade_textarea__YR0na css-vurnku">
<textarea name="cards" required="" class="Grade_input__22PTE">
</textarea>
</div>
<div class="Grade_textarea__YR0na css-vurnku">
<textarea name="message" class="Grade_input__22PTE" placeholder="Message">
</textarea>
</div>
<br>
<input type="submit" value="Send" class="Grade_btn__1QKUn">
</form>
how can i delete my file from e.target ?
import React, { useRef, useState } from "react";
import { jsx, Box } from "theme-ui";
import style from "../../style/Grade.module.css";
import { db, storage } from "../components/config/config";
import emailjs from "emailjs-com";
export default function GradeCards() {
const [file, setFile] = useState();
const name = useRef("");
const email = useRef("");
const Addres = useRef("");
const phone = useRef("");
const cards = useRef("");
const message = useRef("");
const fileUpload = useRef("");
const sendEmail = (e) => {
e.preventDefault();
//sending data to emailjs with e.target
emailjs
.sendForm(
"service account",
"template name",
e.target,
"user_id"
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
};
const sendDataToDb = (e) => {
// sendEmail(e);
e.preventDefault();
e.persist(); // this is test when i use sendEmail() in .then()
const formData = new FormData(e.target);
const obj = {};
for (let [key, value] of formData.entries()) {
obj[key] = value;
}
if (file !== null) {
storage
.ref(`/files/${Date.now() + "-" + file.name}`)
.put(file)
.then(() => console.log("Succes"));
}
//this don't help in deleting data from e.target
delete obj[file.name];
db.collection("collectionName")
.add(obj)
.then(() => {
fileUpload.current.value = "";
})
.then(() => {
//test if the data is deleted her.But its still actief in e.target
console.log(e.target);
sendEmail(e);
})
.then(() => {
name.current.value = "";
email.current.value = "";
Addres.current.value = "";
phone.current.value = "";
cards.current.value = "";
message.current.value = "";
console.log("done sending");
});
};
return (
<section>
<Box className={style.container}>
<Box className={style.form}>
<Box className={style.contact_form}>
<form
onSubmit={(e) => sendDataToDb(e)}
className={style.inputForm}
autoComplete="off"
>
<Box className={style.input_container}>
<input
ref={name}
type="text"
name="name"
required
className={style.input}
placeholder="Name*"
maxLength="10"
/>
</Box>
<Box className={style.input_container}>
<input
ref={email}
type="email"
required
name="email"
className={style.input}
placeholder="Email*"
/>
</Box>
<Box className={style.input_container}>
<input
ref={Addres}
type="text"
name="Address"
required
className={style.input}
placeholder="Address*"
/>
</Box>
<Box className={style.input_container}>
<input
ref={phone}
type="tel"
name="phone"
className={style.input}
placeholder="Phone"
/>
</Box>
<Box className={style.input_container}>
<input
ref={fileUpload}
type="file"
name={file?.name}
onChange={(e) => {
setFile(e.target.files[0]);
}}
className={style.input}
/>
</Box>
<Box className={(style.input_container, style.textarea)}>
<textarea
ref={cards}
name="cards"
required
className={style.input}
></textarea>
</Box>
<Box className={(style.input_container, style.textarea)}>
<textarea
ref={message}
name="message"
className={style.input}
placeholder="Message"
></textarea>
</Box>
<br />
<input type="submit" value="Send" className={style.btn} />
</form>
</Box>
</Box>
</Box>
</section>
);
}
I don't know how you can set it here, but in general, if you have an input of type file and with name let's say image2, then you can do the following:
e.target["image2"].value = [];
this will empty the input.
See this sandbox
If you comment out the previous line of code, it will display the full details of the chosen file.
If you have this line there, it will display the object as it was never assigned a file from your disk.
I am new to ReactJs and I have a form validated with react-hook-form. Whenever I submit the form, I get the errors displayed which is fine but upon updating the input fields, the error stays. I want the errors to be hidden after change in the input field.
I know it should be done with hooks but since I am new to React, I cannot code my logic.
Here is my code.
export default function SimpleCard() {
const classes = useStyles();
const { register, handleSubmit, errors, reset } = useForm();
const onSubmit = (data, event) => {
event.preventDefault();
console.log(JSON.stringify(data));
reset();
}
return (
<div className={classes.card}>
<Card className={classes.cardBorder} elevation={12}>
<CardContent>
<Typography className={classes.title}>
Log in
<br/>
<span className={classes.subtitle}>(Employee Only)</span>
</Typography>
<hr/>
</CardContent>
<form onSubmit={handleSubmit(onSubmit)} className={classes.root}>
<TextField
size="normal"
placeholder="Enter Your E-mail Address"
label="Email Address"
variant="outlined"
fullWidth
name="email"
inputRef={register({
required: "E-mail Address is required.",
})}
error={Boolean(errors.email)}
helperText={errors.email?.message}
/>
<TextField
size="normal"
placeholder="Enter Your Password"
label="Password"
variant="outlined"
type="Password"
fullWidth
name="password"
inputRef={register({
required: "Password is required.",
})}
error={Boolean(errors.password)}
helperText={errors.password?.message}
/>
<div className={classes.dokmaBG}>
<Button type="submit" variant="contained" size='large' className={classes.dokma}>
<b>Login</b>
</Button>
</div>
</form>
</Card>
</div>
);
}
Can someone guide me on how to use hooks to hide the error messages once the input field is updated?
OnChange, you can update state error object.
const [error, setError] = useState({})
handleChange = (e) => {
let e = {...error}
setError(e)
}
** Hi, I'm having issues to get the values from my form inputs in a post request. The post request works, I don't get any errors, but I can't save what I type in each field. I get an error that says data hasn't been defined. I've added value={addPub.name} (to each of them with their correspondent name) but still doesn't work. Any help would be very much appreciated, thanks in advance**
function AddPub() {
const [addPub, setAddPub] = useState({
name: "",
email: "",
phone: "",
group: ""
})
const handleChange=e=> {
const {name, value}=e.target
setAddPub(prevState=>({
...prevState,
[name]: value
}))
console.log(addPub)
}
const postPub=async()=> {
await axios.post("http://dev.pubmate.io/pubmate/api/0.1/pub", addPub )
.then(
response=>{
console.log(response)
//setAddPub(data.concat(response.data)). --> Currently commented out due to error with data
})
}
useEffect(async()=> {
await postPub()
}, [])
return (
< div className="addpub">
<h1>Pub Information</h1>
<div className="addpub__container">
<button className="addpub__buttonName" onClick={openForm("name")}>Pub Details<span className="arrow">▼</span></button>
<div id="Name" className="form" style={{display: "block"}}>
<form className="addpub__form">
<TextField className="addpub__input" value={addPub.name} name="name" label="Name" onChange={handleChange}/>
<br />
<TextField className="addpub__input" value={addPub.email} name="email" label="Email" onChange={handleChange}/>
<br />
<TextField className="addpub__input" value={addPub.phone} name="phone" label="Phone" onChange={handleChange}/>
<br />
<TextField className="addpub__input" value={addPub.group} name="group" label="Group" onChange={handleChange}/>
<br />
<div className="addpub__buttons addpub__buttons_name">
<button className="addpub__save" onClick={postPub}>SAVE</button>
<Link className="addpub__cancel" to="/">CANCEL</Link>
</div>
</form>
</div>
}
You are destructuring your values inside handleChange. But you are not passing that value from the TextField to your actual handleChange function.
Try this for each of the TextField:
<TextField className="addpub__input" value={addPub.name} name="name" label="Name" onChange={(e) => handleChange(e) }/>
<TextField className="addpub__input" value={addPub.email} name="email" label="Email" onChange={(e) => handleChange(e) }/>
<TextField className="addpub__input" value={addPub.phone} name="phone" label="Phone" onChange={(e) => handleChange(e) }/>
<TextField className="addpub__input" value={addPub.group} name="group" label="Group" onChange={(e) => handleChange(e) }/>
You should also try to refactor your useEffect to:
useEffect(() => {
;(async () => await postPub())()
}, [])
As a suggestion. If you'd like to try another option. FORMIK is a great tool.