Clear all fields after submit React js - reactjs

I have the following code in my react app and I need to have empty input areas after submitting. Please assist me.
import { useRef } from 'react';
import './Contact.css';
import emailjs from 'emailjs-com'
import { useState, useEffect } from 'react';
const Contact = () => {
const formRef = useRef();
const [done, setDone] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
emailjs.sendForm(
'service_py6v3mm',
'template_db5q8nx',
formRef.current,
'mJDC1if10C25Z-TZC'
)
.then((result) => {
console.log(result.text);
setDone(true);
}, (error) => {
console.log(error.text);
});
}
return (
<div className="c">
<div className='c-wrapper'>
<div className='c-left'>
<h1 className='c-title'> Let's discuss!</h1>
<div className='c-info'>
<div className='c-info-item'>
<div className="c-info-item">
<img
src="./images/Phone.jpg"
alt=""
className="c-icon"
/>
+12345678 </div>
<div className="c-info-item">
<img className='c-icon'
src="./images/Email.png" alt='Email' />
messimacky#gmail.com
</div>
<div className="c-info-item">
<img className='c-icon'
src="./images/Location.jpeg"
alt=" " />
Addis Ababa, Wolo Sefer, Ethio-China Road, Ethiopia
</div>
</div>
</div>
</div>
<div className='c-right'>
<p className='c-desc'> <b> Get in touch!</b>
</p>
<form ref={formRef} onSubmit={handleSubmit}>
<input type='text' placeholder='Name' name='username' />
<input type='text' placeholder='Subject' name='user_subject' />
<input type='text' placeholder='Your email here... ' name='user_email' />
<textarea rows={5} placeholder='message' name='message' /> <br />
<button>Submit</button>
{done && <p> Thank you I will contact you soon!</p>}
</form>
</div>
</div>
</div>
)
}
export default Contact

You can bind every input value to a state and empty them when you submit it. Here I add an example for the username. You can multiply it and use it.
const [username, setUsername] = useState('Name');
const submitFunctionWhichDeletes = () => {
console.log(username);
setUsername('');
}
<input ... value={username} onChange={e => setUsername(e.target.value)} ... />

const compForm = ()=>{
const [formData,addFormData] = useState({
username:"",
subject:"",
email:"",
message:""
})
cosnt formSubmit =()=>{
// make api call
addFormData({
username:"",
subject:"",
email:"",
message:""
})
}
const formData = (e,filed)=>{
const temp = {...formData}
if (filed === "username"){
temp.username = e.target.value
}
else if(filed === "subject"){
temp.subject = e.target.value
}
else if(filed === "email"){
temp.email = e.target.value
}
else if(filed === "message"){
temp.message = e.target.value
}
addFormData(temp)
}
return(
<>
<input type='text' placeholder='Name' name='username'
value={formData.username} onChange={(e)=>formData(e,username)}/>
<input type='text' placeholder='Subject' name='user_subject'
value={formData.subject} onChange={(e)=>formData(e,subject)}/>
<input type='text' placeholder='Your email here... ' name='user_email'
value={formData.email} onChange={(e)=>formData(e,email)}/>
<textarea rows={5} placeholder='message' name='message'
value={formData.message} onChange={(e)=>formData(e,message)}/>
<button onClick = {(e)=>formSubmit()}>Submit</button>
<>
)
}

Related

Pass data from a form component to another component in react hook

I have the following form, and I need that when submitting the form, its information is displayed in a new component.
Perhaps the issue of redirecting to the other component could be done by creating a route. But I don't know how said component obtains the information of the form
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import {useState, useRef} from 'React'
export default const FormX = () => {
const [formValues, setFormValues] = useState({
name: "",
priceUnitary: "",
size: "",
description: "",
});
const inputFileRef = useRef();
const handleChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formValues);
console.log(inputFileRef.current.files);
};
return (
<>
<form id="formu" onSubmit={handleSubmit} className="row">
<h1>FORM SEND</h1>
<div className="col-md-6">
<label>Name</label>
<input
placeholder="Text input"
name="name"
value={formValues.name}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Size</label>
<input
type="number"
placeholder="Text input"
name="size"
value={formValues.size}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Price Unitary</label>
<input
type="number"
placeholder="Text input"
name="priceUnitary"
value={formValues.priceUnitary}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Description</label>
<input
placeholder="Text input"
name="description"
value={formValues.description}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>File / Image</label>
<input type="file" ref={inputFileRef} />
</div>
<button type="submit" className="color-primary">
Save
</button>
</form>
</>
);
};
Link:
https://codesandbox.io/s/send-form-dcj5v?file=/src/App.js
You can hide your form by change your state on form sumbit and display another component. You have to pass formValue as props in View component. Now think you have better idea what you have to do...
Here i added new component, that display form value on submit
App.js
import { useState, useRef } from "react";
import View from "./View";
const FormX = () => {
const [formValues, setFormValues] = useState({
name: "",
priceUnitary: "",
size: "",
description: ""
});
const [isFormVisible, setIsFormVisible] = useState(true);
const inputFileRef = useRef();
const handleChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formValues);
console.log(inputFileRef?.current?.files);
setIsFormVisible(false);
};
return (
<>
{isFormVisible ? (
<form id="formu" onSubmit={handleSubmit} className="row">
<h1>FORM SEND</h1>
<div className="col-md-6">
<label>Name</label>
<input
placeholder="Text input"
name="name"
value={formValues?.name}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Size</label>
<input
type="number"
placeholder="Text input"
name="size"
value={formValues.size}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Price Unitary</label>
<input
type="number"
placeholder="Text input"
name="priceUnitary"
value={formValues.priceUnitary}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Description</label>
<input
placeholder="Text input"
name="description"
value={formValues.description}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>File / Image</label>
<input type="file" ref={inputFileRef} />
</div>
<button type="submit" className="color-primary">
Save
</button>
</form>
) : (
<View data={formValues} />
)}
</>
);
};
export default FormX;
View.js
import React from "react";
const View = ({ data }) => {
return (
<div>
<p>Name: {data?.name}</p>
<p>priceUnitary: {data?.priceUnitary}</p>
<p>description: {data?.description}</p>
</div>
);
};
export default View;

Invalid hook call. How can I call dispatch?

I'm trying to send data from inputs to redax storage. Why does the dispatch(addChild(parent)) get an error?
Error: Invalid hook call. Hooks can only be called inside of the body of a function component
import {useDispatch} from "react-redux";
import { addChild} from "../../store/actions/actions";
const Form = () => {
const [parent, setParent] = useState([{name: "", age: ""}]);
const [childList, setChildList] = useState([{name: "", age: ""}])
const dispatch = useDispatch;
const handleChange = (e, index) => {
const { name, value } = e.target;
const child = [...childList];
child[index][name] = value;
setChildList(child)
}
const handleSubmit = (e) => {
e.preventDefault();
dispatch(addChild(parent))
}
const addChildElement = ()=> {
setChildList( [...childList, {name: "", age: ""}]);
}
return (
<form className="form" onSubmit={handleSubmit}>
<div className="form__parent">
<div className="form-title">Персональные данные</div>
<div className="form-item">
<input className="form-input" type="text"
value={parent.name}
onChange={(e) => setParent({...parent, name: e.target.value})}
/>
<label className="form-label">Имя</label>
</div>
<div className="form-item">
<input className="form-input" type="number"
value={parent.age}
onChange={(e) => setParent({...parent, age: e.target.value})}
/>
<label className="form-label">Возраст</label>
</div>
</div>
<div className="form__child">
<div className="form__child-head">
<div className="form-title">Дети (макс.5)</div>
<button className="btn add-child-btn" onClick={addChildElement}>Добавить ребенка</button>
</div>
<ul className="form__child-content">
{
childList.map((value, id) => {
return (
<li className="child-list" key={id}>
<div className="form-item">
<input className="form-input" type="text"
name="name"
value={value.name}
onChange={e => handleChange(e, id)}
/>
<label className="form-label">Имя</label>
</div>
<div className="form-item">
<input className="form-input" type="number"
value={value.age}
name="age"
onChange={e => handleChange(e, id)}
/>
<label className="form-label">Возраст</label>
</div>
<button className="remove-list">Удалить</button>
</li>
);
})
}
</ul>
<input className="btn submit" type="submit" value="Сохранить" />
</div>
</form>
);
}
export default Form;`
This is the mistake you have made. call brackets() are missing in your useDispatch declaration.
it should be corrected like below
const dispatch = useDispatch();
Error is totally valid because now your dispatch is not the output of useDispatch. It's useDispatch itself and error is due to useDispatch hook is used inside handleSubmit.

Onchange in React input causes the input to rerender on every letter

So I've created inputs in two functions and on Onchange it gets the value that is being input into them. But anytime I type into the inputs I can only type a letter at a time before it is unfocused and I believe this is because the component keeps on rendering.
I've also realized that whenever I remove the Onchange and value props then everything goes back to normal and I'm able to type everything easily. How would I fix this?
App.js
import style from "./auth.module.css";
import { useEffect, useRef, useState } from "react";
import { useAuthState } from 'react-firebase-hooks/auth';
import { auth, signInWithEmailAndPassword, signInWithGoogle, registerWithEmailAndPassword } from "../../firebase";
import { CSSTransition } from "react-transition-group";
function Auth() {
const [activeMenu, setActiveMenu] = useState("main");
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [user, loading, error] = useAuthState(auth);
const Emailform = () => {
return (
<div className={style.formBox}>
<label className={style.label}>Email:</label>
<form className={style.input}>
<input
type="email"
name="email"
required="true"
value={email}
onChange={(e) => setEmail(e.target.value)} />
</form>
</div>
);
}
const Passform = () => {
return (
<div className={style.formBox}>
<label className={style.label}>Password:</label>
<form className={style.input}>
<input
type="password"
name="password"
required="true"
value={password}
onChange={(e) => setPassword(e.target.value)} />
</form>
</div>
);
}
let domNode = useClickOutside(() => {
setActiveMenu(false);
});
return (
<div className={style.container}>
<Login />
<Signup />
</div>
);
function AuthType(props) {
return (
<a
href={props.link}
className={style.menuItem}
onClick={() => props.goToMenu && setActiveMenu(props.goToMenu)}
>
{props.children}
</a>
);
}
/* Login */
function Login() {
return (
<CSSTransition in={activeMenu === "main"} unmountOnExit timeout={500}>
<div ref={domNode}>
<div className={style.login}>
<h1 className={style.title}>Clip It</h1>
{/* Email and Password */}
<Emailform/>
<Passform/>
<div className={style.button}>
<input
type="submit"
value="Login"
onClick={() => signInWithEmailAndPassword(email, password)} />
<input
type="submit"
value="Login with Google"
onClick={signInWithGoogle} />
</div>
<div className={style.text}>
<p className={style.plink}>Forgot Password</p>
<div>
Need an account?
<AuthType goToMenu="Signup">click here</AuthType>
</div>
</div>
</div>
</div>
</CSSTransition>
);
}
function Signup() {
return (
<CSSTransition in={activeMenu === "Signup"} unmountOnExit timeout={500}>
<div ref={domNode}>
<div className={style.signUp}>
<div className={style.title}> Clip It</div>
<Form label="First Name" type="text" />
<Form label="Last Name" type="Text" />
<Form label="Email" type="email"/>
<Form label="Date of Birth" type="date" />
<Form label="Password" type="password"/>
<Form label="Confirm Password" type="password" />
<div className={style.button}>
<input type="submit" value="Sign Up" />
</div>
<div className={style.text}>
have an
<AuthType goToMenu="main"> account</AuthType>
</div>
</div>
</div>
</CSSTransition>
);
}
}
let useClickOutside = (handler) => {
let domNode = useRef();
useEffect(() => {
let clickListener = (event) => {
if (domNode.current && !domNode.current.contains(event.target)) {
handler();
}
};
document.addEventListener("mousedown", clickListener);
return () => {
document.removeEventListener("mousedown", clickListener);
};
});
return domNode;
};
function Form(props) {
return (
<div className={style.formBox}>
<label className={style.label}>{props.label}:</label>
<form className={style.input}>
<input
type={props.input}
name={props.input}
required="true" />
</form>
</div>
);
}
export default Auth;
Don't put your component definition inside the other component. If you do it, you create a new component at every render.
You need to work around to move Emailform, Passform to outside of Auth.
Checkout this sandbox to experiment
function Auth() {
// 🚫 the bad place to define components
const Emailform = () => {
...
}
// 🚫 the bad place to define components
const Passform = () => {
...
}
}

The input value codes refused to work in react js

What could be wrong with these codes? The input is not working once I add [event.target.name]. If I remove that line of codes, I can see the contents that I type inside the input box. The issue is that I want it to work with this code [event.target.name]. This will enable me pick each inputbox values as entered by the user. There are three input boxes and I need to capture the three values in my useState. Any help on how to write it better?
import React, { useState } from 'react';
import "./addbirthday.css";
import "./home.css";
export default function Addbirthday({setShowAdd}) {
const [inputDatas, setInputData] = useState([
{fullName: '', fullDate: '', relationship: ''}
]);
const handlePublish = () =>{
console.log("Hi ", inputDatas)
}
const handleChangeInput = (index, event) =>{
const values = [...inputDatas];
values[index][event.target.name] = event.target.value
setInputData(values)
}
return (
<div className="container">
<div className= { closeInput? "addContainer" :"addWrapper homeWrapper "}>
<i className="fas fa-window-close" onClick={closeNow} ></i>
{inputDatas.map((inputData, index)=> (
<div key={index} className="addbirth">
<label>Name</label>
<input type="text" name="Fname" placeholder='Namend' value=
{inputData.fullName} onChange = {event => handleChangeInput(index, event)} />
<label>Date</label>
<input type="date" placeholder='Date' name="fdate" value=
{inputData.fullDate} onChange = {event => handleChangeInput(index, event)} />
<label>Relationship</label>
<input type="text" placeholder='Friend' name="frelationship" value=
{inputData.relationship} onChange = {event => handleChangeInput(index, event)}/>
</div>
))}
<button className="addBtn" onClick={handlePublish} >Add</button>
</div>
</div>
)
}
You are not setting the name correctly
Change your input tags name to same as state object name meaning
<input name='fullname' />
I have modified your code a bit. Make it as your own and get it done
Upvote my answer if it helps
https://codesandbox.io/s/jolly-khayyam-51ybe?file=/src/App.js:0-1711
import React, { useState } from "react";
export default function Addbirthday({ setShowAdd }) {
const [inputDatas, setInputData] = useState([
{ Fname: "", fdate: "", frelationship: "" }
]);
const handlePublish = () => {
console.log("Hi ", inputDatas);
};
const handleChangeInput = (index, event) => {
const values = [...inputDatas];
values[index][event.target.name] = event.target.value;
setInputData(values);
console.log(values[index][event.target.name]);
};
return (
<div className="container">
<div className={"addContainer addWrapper homeWrapper"}>
<i className="fas fa-window-close"></i>
{inputDatas.map((inputData, index) => (
<div key={index} className="addbirth">
<label>Name</label>
<input
type="text"
name="Fname"
placeholder="Namend"
value={inputData.fullName}
onChange={(event) => handleChangeInput(index, event)}
/>
<label>Date</label>
<input
type="date"
placeholder="Date"
name="fdate"
value={inputData.fullDate}
onChange={(event) => handleChangeInput(index, event)}
/>
<label>Relationship</label>
<input
type="text"
placeholder="Friend"
name="frelationship"
value={inputData.relationship}
onChange={(event) => handleChangeInput(index, event)}
/>
</div>
))}
<button className="addBtn" onClick={handlePublish}>
Add
</button>
</div>
</div>
);
}

the state inside hooks are not updated for first time on form submit in react

I was trying to implement contactUS form in react using hooks.Contact us form is placed inside hooks.When I first submit the form the state in hooks are not updated ,when I click 2nd time states are set .and I am returning state to class component there api call are made.
//contactushook.js
import React, { useState } from 'react';
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState([]);
const handleSubmit = (event) => {
event.preventDefault();
setData({ name: document.getElementById('name').value, email: document.getElementById('email').value, message: document.getElementById('message').value });
console.log(data);
parentCallBack(data);
}
return <React.Fragment>
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input id="name" type="text" placeholder="enter the name"></input>
</div>
<div>
<input id="email" type="email" placeholder="enter the email"></input>
</div>
<div>
<textarea id="message" placeholder="Type message here"></textarea>
</div>
<button type="submit" >Submit</button>
</form>
</div>
</React.Fragment >
}
export default ContactUshook;
//contactus.js
import React, { Component } from 'react';
import ContactUshook from './hooks/contactushook';
import '../contactUs/contactus.css';
class ContactComponent extends Component {
onSubmit = (data) => {
console.log('in onsubmit');
console.log(data);
}
render() {
return (
<div>
<h4>hook</h4>
<ContactUshook parentCallBack={this.onSubmit}></ContactUshook>
</div>
);
}
}
export default ContactComponent;
Stop using document queries and start using state instead!
Your ContactUshook component should look like this:
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState({ name: '', email: '', message: '' });
const handleSubmit = () => {
event.preventDefault();
parentCallBack(data);
}
const handleChange = (event, field) => {
const newData = { ...data };
newData[field] = event.target.value;
setData(newData);
}
return (
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input
id="name"
type="text"
value={data.name}
placeholder="enter the name"
onChange={(e) => handleChange(e,'name')} />
</div>
<div>
<input
id="email"
type="email"
value={data.email}
placeholder="enter the email"
onChange={(e) => handleChange(e,'email')} />
</div>
<div>
<textarea
id="message"
value={data.message}
placeholder="Type message here"
onChange={(e) => handleChange(e,'message')} />
</div>
<button type="submit" >Submit</button>
</form>
</div>
);
}

Resources