Hi I am learning Reactjs, redux, and I want to simply print to console.log the username and password for this form.
I have tried console.log(e.target.user.value) but I a getting no results.
here is the handle function.
and then the Form and 2 fields.
how can I print the value of username and password in the handleSubmit function ?
Try Below Code:
handleSubmit = values => {
console.log('values',values);
//Here you will get values in values.username & values.password
}
render(){
const { handleSubmit } = this.props;
return(
<form onSubmit={handleSubmit(this.handleSubmit)}>
<div className="form-inputs">
<Field type="text" label="Name" name="username" data-fieldname="username"
component={bootstrapFormField} placeholder="Username" />
<Field type="password" label="Password" name="password" data-
fieldname="password" component={bootstrapFormField}
placeholder="Password" />
</div>
<div className="form-actions text-right">
<button type="submit" className="btn btn-submit green">
Sign In
</button>
</div>
</form>
)
}
Related
onChange event won't work in input react when trying to call a function! any help please
I'm getting values using watch()
my point is when onChange in input I want to get the whole value
const Valid = () =>{
let Username = watch("Username")
console.log(Username)
const {data} = useQuery(CHECK_AVAILABLITY, {
variables:{Username},
}
)
<form>
<Input onChange={Valid} type="text" {...register("Username")} placeholder="Username " />
<Input type="password" placeholder="Password" />
<Button type="submite" >Sign Up</Button>
</form>
I assume that you are using react hook form.
you can use the watch and the useEffect method
let Username = watch("Username")
useEffect(() => {
console.log('username value', Username);
},[Username]);
return(
<form>
<Input type="text" {...register("Username")} placeholder="Username" />
<Input type="password" placeholder="Password" />
<Button type="submit">Sign Up</Button>
</form>
);
Try to put it like that
<Input onChange={(e) => Valid(e.target.value)} type="text" {...register("Username")} placeholder="Username " />
and then get the variable in the params of the Valid function
exemple :
const valid = (username) => {
console.log(username)
}
I am having an issue when I submit my form it puts all of the form data into my URL instead of sending it to my backend. I'm not sure what the issue is at first I thought it was because I didn't have a method="post" in the form tag but that didn't fix my issue because it tried to send the form data to localhost:3000/register instead of localhost:5000/register. Any help would be appreciated.
Bellow is my current Frontend code.
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'
import '../css/register.css';
import {IoMdArrowRoundBack} from 'react-icons/io'
import { useState } from 'react'
import axios, { Axios } from 'axios';
const Register = () => {
const [emailReg, setEmailReg] = useState("");
const [usernameReg, setUsernameReg] = useState("");
const [passwordReg, setPasswordReg] = useState("");
const register = () => {
Axios.post('http://localhost:5000/register', {
email: emailReg,
username: usernameReg,
password: passwordReg,
}).catch(function (error) {
console.log(error);
});
};
return (
<div className='background-image'>
<div className='back-button'>
<Link to='/'>
<IoMdArrowRoundBack id='back-arrow' />
<h3>Home</h3>
</Link>
</div>
<div className="container-wrapper">
<div className="container">
<h1>Create Account</h1>
<div className="wrapper">
<form>
<div className="textarea" id="email">
<input
type="email"
onChange={(e) => {
setEmailReg(e.target.value);
}}
name="email"
id="authentactor-email"
placeholder="Email"
defaultValue=""
required
/>
</div>
<div className="textarea" id="username">
<input
type="text"
onChange={(e) => {
setUsernameReg(e.target.value);
}}
name="name"
id="authentactor-text"
placeholder="Username"
defaultValue=""
required
/>
</div>
<div className="textarea" id="password">
<input
type="password"
onChange={(e) => {
setPasswordReg(e.target.value);
}}
name="password"
id="authentactor-password"
placeholder="Password"
defaultValue=""
required
/>
</div>
<div id="button-wrapper">
<button id="button" onClick={register}>Create Account</button>
</div>
</form>
<div className='bottom-text-wrapper'>
<h4>Already have an account? <Link to='/login'>Login Here</Link></h4>
</div>
</div>
</div>
</div>
</div>
)
}
export default Register
According to HTML Living Standard
The missing value default and invalid value default are the Submit Button state.
You can find more information on this question but basically adding type="button" to your Create Account button should do the job.
(so something like <button id="button" type="button" onClick={register}>Create Account</button>)
I figured it out for some reason I can't have the "name" tag in my input fields like it is below.
<div className="textarea" id="password">
<input
type="password"
onChange={(e) => {
setPasswordReg(e.target.value);
}}
name="password"
id="authentactor-password"
placeholder="Password"
defaultValue=""
required
/>
</div>
<div id="button-wrapper">
<button onClick={register} id="button">Create Account</button>
</div>
As soon as I removed the "name" tags I was able to POST my form to the backend and I only get a question mark in my url now instead of all the form data. To fix the question mark I had to set button type="button".
correct code below.
<div className="textarea" id="password">
<input
type="password"
onChange={(e) => {
setPasswordReg(e.target.value);
}}
id="authentactor-password"
placeholder="Password"
defaultValue=""
required
/>
</div>
<div id="button-wrapper">
<button type="button" onClick={register} id="button">Create Account</button>
</div>
My code has got 3 input fields i.e first name, last name, email and 1 useState to hold its value, I want to remove the div part containing all the input fields after i hit Sign up and display only Thank You
My code has got 3 input fields i.e first name, last name, email and 1 useState to hold its value, I want to remove the div part containing all the input fields after i hit Sign up and display only Thank You
Before signing up
AFter signing up
const Home = () => {
const [saveInput, setInput] = useState({
fname: '',
lname: '',
email: '',
});
const [message, setMessage] = useState('enter email');
const inputFields = (event) => {
const { value, name } = event.target;
setInput((preValue) => ({
...preValue,
[name]: value,
}));
};
const onSubmits = (event) => {
setMessage('thanks');
};
return (
<div className="homeMain">
<div className="row">
<img
className="home_img"
src="https://i.pinimg.com/originals/53/b5/d7/53b5d70023efa05ec6797b25df413b73.jpg"
/>
<h1 className="home_h1 text-center">Maryam's Restaurant</h1>
<Link
style={{
color: 'white',
textDecoration: 'inherit',
textAlign: 'center',
}}
to="/Restaurant"
className="home_button"
>
View Menu
</Link>
<h2 className="home_h2 text-center">
Binging with Babish is a cooking show dedicated to discovering what
the delectable (and occasionally horrible) foods from fiction actually
taste like.
</h2>
{receipeList.map((curElem) => (
<div className="home2Main">
<img className="home_img2" src={curElem.img} />
<p className="home2Mainp1">{curElem.h1}</p>
<p className="home2Mainp2">{curElem.date}</p>
</div>
))}
</div>
<homeMainDetails />
<div className="home4Main">
<h4>
<bold>Subscribe</bold>
<br />
<small>
Sign up with your email address to receive news and updates.
</small>
</h4>
<input
className="home4MainInput"
name="fname"
onChange={inputFields}
value={saveInput.fname}
type="text"
placeholder="First Name"
/>
<input
className="home4MainInput"
name="lname"
onChange={inputFields}
value={saveInput.lname}
type="text"
placeholder="Last Name"
/>
<input
className="home4MainInput"
name="email"
onChange={inputFields}
value={saveInput.email}
type="text"
placeholder="Email Address"
/>
<button onClick={onSubmits}>Sign Up</button>
<h4 className="home4Mainh4">
<small>{message}</small>
</h4>
</div>
</div>
);
};
export default Home;
You could use another state to indicate your submit state.
This way you can hold state value without affecting to the message state:
Use another state:
const [isSubmited, setIsSubmited] = useState(false);
Change that state when you submit:
const onSubmits = (event) => {
setMessage('thanks');
setIsSubmited(true);
};
Then render it conditionally:
{isSubmited ? (
<div className="home4Main">
...
</div>
) : message}
You can do it with a basic condition message !== "Thank you" like this:
<div className="home4Main">
{message !== "Thank you" && (
<>
<h4>
<bold>Subscribe</bold>
<br />
<small>Sign up with your email address to receive news and updates.</small>
</h4>
<input
className="home4MainInput"
name="fname"
onChange={inputFields}
value={saveInput.fname}
type="text"
placeholder="First Name"
/>
<input
className="home4MainInput"
name="lname"
onChange={inputFields}
value={saveInput.lname}
type="text"
placeholder="Last Name"
/>
<input
className="home4MainInput"
name="email"
onChange={inputFields}
value={saveInput.email}
type="text"
placeholder="Email Address"
/>
<button onClick={onSubmits}>Sign Up</button>
</>
)}
<h4 className="home4Mainh4">
<small>{message}</small>
</h4>
</div>
And update message
const onSubmits = (event) => {
setMessage('Thank you');
};
Create a useState that contains the value on the state of the form.
const [isSubmited, setIsSubmited] = useState(false);
Then use this value in the JSX to conditional render the elements you want to display.
isSubmitted ? <div> Thank You! </div> : <div> your form.... </div>
You can call setIsSubmited(true) when you submit the form.
I have a login component where the user can log in with email and password. In the database, the user have following properties.
1.userID
2.Email
3.Password
I want to get the userid back from the API according to the user login. Cansome genius help me with this?
my login component:
export default class Login extends Component {
state = {};
submitHandler = e => {
e.preventDefault()
const logingdata ={
email : this .Email,
password: this .Password
}
axios
.post('/api/UserLogin', logingdata)
.then(response => {
console.log(response); //to print response in console in developper tool
//const currentuser = JSON.parse(atob(response.data.token.split(".")[1]));
localStorage.setItem('login', response.data.token);
console.log(this.email);
})
.catch(error => {
console.log(error => console.log(error.response.data))
})
}
render() {
return (
<div className="outer">
<div className="inner">
<form onSubmit={ this.submitHandler}>
<h3>Log in</h3>
<div className="form-group">
<label>Email</label>
<input type="text" className="form-control" placeholder="Enter email" onChange ={ e => this.Email = e.target.value} />
</div>
<div className="form-group">
<label>Password</label>
<input type="text" className="form-control" placeholder="Enter password" onChange ={ e => this.Password = e.target.value} />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<br></br>
<button type="submit" className="btn btn-dark btn-lg btn-block">Sign in</button>
<p className="forgot-password text-right">
Forgot <Link to= "/Forgotpassword" >password?</Link>
</p>
</form>
</div>
</div>
);
}
}
EDIT:
console response hen login: (it shows only username and password)
I have this project I am working on. The form was working before I added React reCAPTCHA but now, the form is not submitting and reCAPTCHA keeps showing the error message after being checked and submit button is clicked on.
Here is the code:
const validationSchema = yup.object().shape({
name: yup.string().required('Your name is required.'),
email: yup.string().email('Please enter a valid email address.').required('Email is required'),
comment: yup.string().required('No comment entered yet.'),
recaptcha: yup.string().required('Confirm that you are human.'),
});
const {
'article-comment-name': name,
'article-comment-email': email,
'article-comment-comment': commentInput,
'article-comment-submit': submit,
} = keyBy(commentForm?.form?.inputs, KEY);
return (
<div>
<p className="text text-success text-center">{msg && <p>Your comment has been added.</p>}</p>
<Formik
initialValues={formInitialValues}
onSubmit={(comment, { resetForm }) => {
handleVerify();
submitComment(comment);
resetForm();
commentCreated();
}}
validationSchema={validationSchema}
>
{({ values: comment, handleChange, handleSubmit, errors, touched }) => (
<form id="add-comment" className="add-comment" onSubmit={handleSubmit}>
<fieldset>
<div className="row">
<div className="col-md-6">
<label>
{name.label}:{' '}
<span className="text-danger">
{errors.name && touched.name && errors.name}
</span>
</label>
<input type="text" name="name" value={comment.name} onChange={handleChange} />
</div>
<div className="col-md-6">
<label>
{email.label}:{' '}
<span className="text-danger">
{errors.email && touched.email && errors.email}
</span>
</label>
<input type="text" name="email" value={comment.email} onChange={handleChange} />
</div>
</div>
<div>
<label>
{commentInput.label}:{' '}
<span className="text-danger">
{errors.comment && touched.comment && errors.comment}
</span>
</label>
<textarea
name="comment"
cols={40}
rows={3}
value={comment.comment}
onChange={handleChange}
></textarea>
</div>
<Recaptcha
sitekey="mysitekey"
verifyCallback={handleVerify}
render="explicit"
/>
<span className="text-danger">{verify && touched.recaptcha && errors.recaptcha}</span>
</fieldset>
<br />
<button type="submit" className="theme-btn">
<span>{submit.label}</span>
</button>
<div className="clearfix"></div>
</form>
)}
</Formik>
</div>
I have checked the callback and It's working fine on that end. The main problem is that the form is not submitting. It keeps showing this message as stated: Confirm that you are human.
What could be the issue?
In Formik setting the values or errors are all binded with the name prop. The name prop of an element should match with one of the keys with the values . You have validationSchema for recaptcha but it is not associated with your Recaptcha component.
<Recaptcha
sitekey="mysitekey"
verifyCallback={handleVerify}
render="explicit"
/>
Submission in formik triggers a series of events . Please read this Formik Form Submission