I have a code for Registration Page. Where I'm trying to send data to database by using this.setState and this.state but everytime I run the code Its showing some error in onSubmit Function about this.state . Why I'm getting this error please tell me. I've a project to submit and I'm stuck on this
import React, {Component} from 'react';
import {register} from './UserFunctions';
class Register extends Component {
constructor() {
super()
this.state = {
first_name: '',
last_name: '',
email: '',
password: ''
};
this.onChange = this.onChange.bind(this)
this.onChange = this.onChange.bind(this)
}
onChange(e){
this.setState({[e.target.name]: e.target.value});
}
onSubmit(e){
e.preventDefault()
const user = {
first_name: this.state.first_name, [error line]
last_name: this.state.last_name,
email: this.state.email,
password: this.state.password
}
register(user).then(res => {
if (res) {
this.props.history.push('/login');
}
})
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6 mt-5 mx-auto">
<form noValidate onSubmit={this.onSubmit}>
<h1 className="h3 mb-3 font-weight-normal">Please Sign in!</h1>
<div className="form-group">
<label htmlFor="first_name">First Name</label>
<input type="text"
className="form-control"
name="first_name"
placeholder="First Name"
value={this.state.first_name}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="last_name">Last Name</label>
<input type="text"
className="form-control"
name="last_name"
placeholder="Last Name"
value={this.state.last_name}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email Address</label>
<input type="email"
className="form-control"
name="email"
placeholder="Enter Email"
value={this.state.email}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password"
className="form-control"
name="password"
placeholder="Enter Password"
value={this.state.password}
onChange={this.onChange}
/>
</div>
<button type="submit"
className="btn btn-lg btn-primary btn-block">
Register
</button>
</form>
</div>
</div>
</div>
)
}
}
export default Register
Please tell me what should I do to solve this problem.
You have to bind it like you did with onChange
this.onSubmit = this.onSubmit.bind(this)
You forgot to do it probably, when copying onChange.
Related
I have created a register page and tried to access the input value using handleChange event but the form is not taking any input. If the 'value=""' field of form elements is commented or their values are set null then the form is working. I tried by declaring a global
const {name, email, phone, work, password, cpassword} = user;
and passed the attributes to their respective value="" field but still not worked. How to solve this issue?
This is the code of my signup page.
import React ,{useState} from "react";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap";
import "../css/Signup.css"
import img from "../imgs/register.png"
import { NavLink } from "react-router-dom";
const Signup = ()=>{
const [user, setUser] = useState({
name:"", email:"", phone:"", work:"", password:"", cpassword:""
});
let name, value;
const handleChange = (event)=>{
name = event.target.name;
value = event.target.value;
setUser({...user, [name]:value});
}
const postData = (event)=>{
}
return (
<section className="section-container">
<div className="container">
<div className="myCard">
<div className="row">
<div className="col-md-6">
<div className="myLeftCtn">
<form className="myForm text-center" method="POST">
<header>Sign Up</header>
<div className="form-group">
<i className="fas fa-user"></i>
<input className="myInput" type={"text"}
value={user.name}
onChange={handleChange}
placeholder="Username" id="username" required></input>
</div>
<div className="form-group">
<i className="fas fa-envelope"></i>
<input className="myInput" type={"text"}
value={user.email}
onChange={handleChange}
placeholder="Email" id="email" required></input>
</div>
<div className="form-group">
<i className="fas fa-phone"></i>
<input className="myInput" type={"text"}
value={user.phone}
onChange={handleChange}
placeholder="Mobile Number" id="phone" required></input>
</div>
<div className="form-group">
<i className="fas fa-user-tie"></i>
<input className="myInput" type={"text"}
value={user.work}
onChange={handleChange}
placeholder="Profession" id="work" required></input>
</div>
<div className="form-group">
<i className="fas fa-lock"></i>
<input className="myInput" type={"password"}
value={user.password}
onChange={handleChange}
placeholder="Password" id="password" required></input>
</div>
<div className="form-group">
<i className="fas fa-lock"></i>
<input className="myInput" type={"password"}
value={user.cpassword}
onChange={handleChange}
placeholder="Confirm Password" id="cpassword" required></input>
</div>
<div className="form-group">
<label>
<input id="check_1" name="check_1" type={"checkbox"} required />
<small>I read and agree to Terms and Conditions</small>
<div className="invalid-feedback">You must check the box.</div>
</label>
</div>
<input type={"submit"} onClick={postData} className="butt" value={"Create Account"}/>
</form>
</div>
</div>
<div className="col-md-6">
<div className="box">
<figure>
<img className="signup-img" src={img} alt="signup-img"></img>
</figure>
<div className=""><NavLink className="butt_out" to="/login">I am already registered</NavLink></div>
</div>
</div>
</div>
</div>
</div>
</section>
)
}
export default Signup;
Everything looks great.Accept this line of code
<input type="submit" onClick={postData} className="butt" value={"Create Account"}/>
Your event.target.name will always be "". You will need to add name attribute to your form like so:
<input className="myInput" type={"text"} name="name"
value={user.name}
onChange={handleChange}
placeholder="Username" id="username" required></input>
Alternatively, you can use event.target.id, but you will need to update your form so it matches the user object. E.g. input for username should have an id of "name"
the name is doesn't passed
Example:
<input className="myInput" type={"text"} name="email" value={user.email}
onChange={handleChange} placeholder="Email" id="email" required>
</input>
and you don't need to declare let name, value;
outside the function
Function should look like :
const handleChange = (event) => {
const name = event.target.name;
const value = event.target.value;
setUser({...user, [name]:value});
}
or
const handleChange = (event) => {
setUser({...user, [event.target.name]:event.target.value});
}
I am making a registration form in react and trying to send a request using the axios API. I'm getting no errors in the code, but when I click the sign up button, then go to the console, then go to the network, I see that it's failing to load the response data.
The error I am getting is:
Failed to load response data : No data found for resource with given identifier
export class Register extends React.Component {
handleSubmit = e => {
e.preventDefault();
const data = {
first_name: this.firstName,
last_name: this.lastName,
email: this.email,
password: this.password,
password_confirm: this.confirmPassword
};
axios.post('http://localhost:8000/Register', data).then(
res => {
console.log(res)
}
).catch(
err => {
console.log(err);
}
)
};
render() {
return (
<form onSubmit={this.handleSubmit} >
<h3>Sign Up</h3>
<div className="form-group">
<label> First Name</label>
<input type="text" className="form-control" placeholder="First Name"
onChange={e => this.firstName = e.target.value} />
</div>
<div className="form-group">
<label> Last Name</label>
<input type="text" className="form-control" placeholder="Last Name"
onChange={e => this.lastName = e.target.value} />
</div>
<div className="form-group">
<label> Email</label>
<input type="email" className="form-control" placeholder="Email"
onChange={e => this.email = e.target.value} />
</div>
<div className="form-group">
<label> Password</label>
<input type="password" className="form-control" placeholder="Password"
onChange={e => this.password = e.target.value} />
</div>`
<div className="form-group">
<label> Confirm Password</label>
<input type="password" className="form-control" placeholder="Confirm Password"
onChange={e => this.confirmPassword = e.target.value} />
</div>`
<button className="btn btn-primary btn-block" > Sign Up</button>
</form >
);
}
}
export default Register;
I have successfully executed the post Axios call using hooks in React js. But I am not sure how to show the success message or error message catching from the api response and show it below the form. The message should be exactly what is written in the API response.
My Messageform:
const MessageForm = () => {
const url = "https://example.herokuapp.com/api/messages"
const [data, setData] = useState({
first_name: "",
last_name: "",
email:"",
phone:"",
msz:""
})
function submit(e){
e.preventDefault();
axios.post(url,{
first_name: data.first_name,
last_name:data.last_name,
email:data.email,
phone:data.phone,
msz:data.msz
})
.then(res=>{
console.log(res.data)
})
setData({
first_name: "",
last_name: "",
email:"",
phone:"",
msz:""
});
}
function handle(e){
const newdata = {...data}
newdata[e.target.id] = e.target.value
setData(newdata)
console.log(newdata)
// setData("");
}
return (
<div className="message-form">
<div className="container">
<div className="title">
<span>Contact Now</span>
<div className="main-title">Send us a message</div>
</div>
{/* form start */}
<form action="" className="apply" onSubmit={(e)=> submit(e)}>
<div className="row row-1">
{/* Name here */}
<div className="input-field name">
<label htmlFor="Name">First Name</label>
<input onChange ={(e) => handle(e)} value = {data.first_name}
required
type="text"
placeholder="Your First Name"
name="Name"
id="first_name"
/>
</div>
<div className="input-field name">
<label htmlFor="Name">Last Name</label>
<input onChange ={(e) => handle(e)} value = {data.last_name}
required
type="text"
placeholder="Your Last Name"
name="Name"
id="last_name"
/>
</div>
</div>
<div className="row row-2">
{/* phone here */}
<div className="input-field phone">
<label htmlFor="Phone">Phone</label>
<input onChange ={(e) => handle(e)} value = {data.phone}
required
type="text"
placeholder="Your Phone Here"
name="Phone"
id="phone"
/>
</div>
{/* Email here */}
<div className="input-field email">
<label htmlFor="Email">Email Address</label>
<input onChange ={(e) => handle(e)} value = {data.email}
required
type="text"
placeholder="Your Email Address"
name="Email"
id="email"
/>
</div>
</div>
{/* date select */}
<div className="row row-3">
{/* Message here */}
<div className="input-field message">
<label htmlFor="Message">Message</label>
<textarea onChange ={(e) => handle(e)} value = {data.msz}
required
placeholder="Enter Message Here"
name="Message"
id="msz"
/>
</div>
</div>
{/* submit button */}
<ExploreButton hoverText="Submit" hover="hoverTrue">
Send Now
</ExploreButton>
</form>
{/* Form end */}
</div>
</div>
);
};
export default MessageForm;
This is the response that I get from the api
Here I want to catch the string written in message and render it in the UI. I am new to react and I am not sure how to do that.
Your API is returning a response stream, you need to use the response .json() method to read it to completion. But before you do that, you should store the response status code, as it becomes inaccessible after you parse the response JSON.
axios.post(url,{
first_name: data.first_name,
last_name:data.last_name,
email:data.email,
phone:data.phone,
msz:data.msz
}).then(response => {
let statusCode = response.status,
success = response.ok;
response.json().then(response => {
if(!success){
//handle errors here
console.log(response.message)
return;
}
// handle successful requests here
console.log(response.message)
})
}).catch((error) => {
// catch any unexpected errors
console.log(error);
})
Some general advice. you should try to separate your Axios requests into an independent function and make it reusable, or you will run into issues in the future if you decide to handle your API responses differently in the future.
I cleaned it up a bit, so its easier to understand. The short answer is use an additional "useState" hook to store the messages. Then have a logical operator (in the return section above row-1) to check if messages exists & display them.
Warning: None of this code was tested.
const INITIAL = {
first_name: "",
last_name: "",
email: "",
phone: "",
msz: ""
}
const MessageForm = () => {
const url = "https://example.herokuapp.com/api/messages"
const [data, setData] = useState(INITIAL);
const [message, setMessage] = useState(null);
function handleSubmit(e) {
e.preventDefault();
setMessage(null);
axios.post(url, data)
.then(res => {
setData(res.data);
setMessage(res.message);
})
.catch(err => {
setMessage(err.message);
})
}
function handleChange(e) {
const { id, value } = e.target; //destructuring
setData({...data, [id]:value})
}
return (
<div className="message-form">
<div className="container">
<div className="title">
<span>Contact Now</span>
<div className="main-title">Send us a message</div>
</div>
{/* form start */}
<form className="apply" onSubmit={handleSubmit}>
{message && <div>{message}</div>}
<div className="row row-1">
{/* Name here */}
<div className="input-field name">
<label htmlFor="Name">First Name</label>
<input onChange={handleChange}
value={data.first_name}
required
type="text"
placeholder="Your First Name"
name="Name"
id="first_name"
/>
</div>
<div className="input-field name">
<label htmlFor="Name">Last Name</label>
<input onChange={handleChange}
value={data.last_name}
required
type="text"
placeholder="Your Last Name"
name="Name"
id="last_name"
/>
</div>
</div>
<div className="row row-2">
{/* phone here */}
<div className="input-field phone">
<label htmlFor="Phone">Phone</label>
<input onChange={handleChange}
value={data.phone}
required
type="text"
placeholder="Your Phone Here"
name="Phone"
id="phone"
/>
</div>
{/* Email here */}
<div className="input-field email">
<label htmlFor="Email">Email Address</label>
<input onChange={handleChange}
value={data.email}
required
type="text"
placeholder="Your Email Address"
name="Email"
id="email"
/>
</div>
</div>
{/* date select */}
<div className="row row-3">
{/* Message here */}
<div className="input-field message">
<label htmlFor="Message">Message</label>
<textarea onChange={handleChange} value={data.msz}
required
placeholder="Enter Message Here"
name="Message"
id="msz"
/>
</div>
</div>
{/* submit button */}
<ExploreButton hoverText="Submit" hover="hoverTrue">
Send Now
</ExploreButton>
</form>
{/* Form end */}
</div>
</div>
);
};
export default MessageForm;
I am new to Reactjs. I just wrote this code and onSubmit function is not working. I am not getting if it's fault of register or form handleSubmit.Might be error in this line where the form tag is written.
Please guide and let me know of solutions.react-hook-form version is 7.14
React version is 17.02
FieldArray.js
import React, { Fragment } from "react";
import { useForm } from "react-hook-form";
function FieldArray() {
const { register, handleSubmit } = useForm();
const basicform = (
<div className="card">
<div className="card-header">Basic Information</div>
<div className="card-body">
<div>
<div className="form-group">
<label htmlFor="fullname">Full Name</label>
<input
type="text"
className="form-control"
id="fullname"
name="fullname"
{...register("fullname")}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input
type="email"
className="form-control"
id="email"
name="email"
{...register("email")}
/>
</div>
<div className="form-group">
<label htmlFor="phone">Phone Number</label>
<input
type="text"
className="form-control"
id="phone"
name="phone"
{...register("phone")}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
name="password"
{...register("password")}
/>
</div>
</div>
</div>
</div>
);
const onSubmit = data => {
console.log('hjhhhh');
console.log(data);
}
return (
<div className="App">
<div className="container py-5">
<form onSubmit={handleSubmit(onSubmit)}>{basicform}</form>
<button className="btn btn-primary" type="submit">Submit</button>
</div>
</div>
);
}
export default FieldArray;
We have to wrap the submit button inside the Form tag
<form onSubmit={handleSubmit(onSubmit)}>
{basicform}
<button className="btn btn-primary" type="submit">
Submit
</button>
</form>
Sandbox - https://codesandbox.io/s/silly-cori-t94eu?file=/src/react-hook-form.jsx
I have a full form written out with other components for the success of the submission and validation, but now I want to connect to Emailjs so I can receive the email in my actual gmail. Heres what the EmailJs code wants me to add to my code but Im not sure how to pass 2 arguments together and make it work.
function sendEmail(e) {
e.preventDefault();
emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', e.target, 'YOUR_USER_ID')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
}
and here is my code
import React from 'react'
import useForms from './useForms'
import validate from './validateInfo'
const FormContact = ({submitForm}) => {
const { handleChange, values, handleSubmit, errors} = useForms(submitForm, validate);
return (
<div className="form-content-right">
<form action="" className="form" onSubmit={handleSubmit}>
<h6>Get in contact with us!</h6>
<div className="form-inputs">
<label htmlFor="name" className="form-label">
Full Name:
</label>
<input id='name'
type="text"
name='name'
className="form-input"
placeholder='Name'
value={values.name}
onChange={handleChange}
/>
{errors.name && <p>{errors.name}</p>}
</div>
<div className="form-inputs">
<label htmlFor="email" className="form-label">
Email Address:
</label>
<input id='email'
type="email"
name='email'
className="form-input"
placeholder='Email'
value={values.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
</div>
<div className="form-inputs">
<label htmlFor="number" className="form-label">
Contact Number:
</label>
<input id='number'
type="tel"
name='number'
className="form-input"
placeholder='Contact number' />
</div>
<div className="form-inputs">
<label htmlFor="country" className="form-label">
Country:
</label>
<input id='country'
type="country"
name='country'
className="form-input"
placeholder='Country'
value={values.country}
onChange={handleChange}
/>
{errors.country && <p>{errors.country}</p>}
</div>
<div className="form-inputs">
<label htmlFor="message" className="form-label">
Message:
</label>
<textarea id='message'
type="message"
name='message'
className="form-input"
placeholder='Enter message here'
value={values.message}
onChange={handleChange}
/>
</div>
<button className="form-input-btn" type='submit' >
Contact Us
</button>
</form>
</div>
)
}
export default FormContact
I need handleSubmit for my code to work but also somehow need to add "sendEmail" to that same argument inside onSubmit
You can create an anonymous function that calls both your needed functions:
<form action="" className="form" onSubmit={(e) => {handleSubmit(e); sendEmail(e);}} >