how to fix onChange event won't work in input react - javascript

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)
}

Related

Take user input and onclick button it should load url according to input in new tab in react js

I want to take city name as input and on button click it should call specific url https://www.google.com/maps/search/tourist+places+in+ mumbai with ending url with input value in react. It should open the url in new tab
Destination.jsx (file name)
import React from 'react'
const Destination = () => {
return (
<div>
<h1>Destination</h1>
<input type="text" name="place" class="form-control" id="place" placeholder="Enter place" />
<button type="Submit" id="submit"> Search </button>
</div>
)
}
export default Destination
You can do like this to search places in new tab.
import React from 'react';
const Destination = () => {
const handleSearch = (e) => {
window.open(
`https://www.google.com/maps/search/tourist+places+in+${e.target.place.value}`,
'_blank'
);
};
return (
<div>
<h1>Destination</h1>
<form onSubmit={handleSearch}>
<input
type="text"
name="place"
class="form-control"
id="place"
placeholder="Enter place"
/>
<button type="Submit" id="submit">
Search
</button>
</form>
</div>
);
};
export default Destination;
Create a state:
const [destination, setDestination] = useState("");
Then use this state to populate your search query like this:
<input type="text" name="place" class="form-control" id="place" placeholder="Enter place" value={destination} onChange={(e) => setDesitnation(e.target.value)} />
and then when you submit you can call a custom function on the onClick() of button:
<button id="submit" onClick={searchDestination}> Search </button>
The function might go somwthing like this:
const searchDestination = () => {
window.location.href = `https://www.google.com/maps/search/tourist+places+in+${destination}`;
}

When ever I submit my form I get the form data in my URL instead of it posting to my backend

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>

Conditional rendering of a div based on state in react

Below is a authentication component that handles both registering and login of a user into an application. The approach used was to conditionally render a div based on whether a user had signed up in the application before or they are a new user. The div doesn't change based on the initial state and based on the conditions set. In this case, the isSignUp state is false therefore the user hasn't signed up before hence all the fields are supposed to be available for data input by the user but the fields have been ommited. Below is the code
const {isSignUp, setisSignUp} = useState(false);
<form onSubmit = {handleSubmit} className = 'form'>
{isSignUp && (
<div className='auth-form-field'>
<input
name="Full Name"
type="text"
placeholder="Full Name"
className = "form-input"
onChange={handleChange}
required
/>
</div>
)}
<div className='auth-form-field'>
<input
name="Email"
type="text"
placeholder="Email"
className = "form-input"
onChange={handleChange}
required
/>
</div>
{ isSignUp && (
<div className='auth-form-field'>
<input
name="User Name"
type="text"
placeholder="User Name"
className = "form-input"
onChange={handleChange}
required
/>
</div>)
}
<div className = 'auth-form-field'>
<input
name="Password"
type="password"
placeholder="Password"
className = "form-input"
onChange={handleChange}
required
/>
</div>
{isSignUp && (
<div className = 'auth-form-field'>
<input
name="Confirm Password"
type="password"
placeholder="Confirm Password"
className = "form-input"
onChange={handleChange}
required
/>
</div>)
}
</form>
Your syntax of useState is incorrect here
Correct syntax:
const [isSignUp, setisSignUp] = useState(false);
The Correct syntax to use useState is with square brackets, like this
const [isSignup, setIsSignUp] = useState(false);

react-hook-form doesn't work when using material UI button

This is my code without material UI button:
const {register, handleSubmit} = useForm();
const onSubmit = (data) => {
console.log(data)
}
const handleChange = (e) => {
console.log(e.target.files)
}
...
<form id="myFile" onSubmit={handleSubmit(onSubmit)}>
<input id="file1" type="file" {...register("file1")} onChange={handleChange}/>
<input type="submit"/>
</form>
This works for me, but when I try to add material UI button instead of input, I get onChange value but when I click submit. I don't get any form data.
const {register, handleSubmit} = useForm();
const onSubmit = (data) => {
console.log(data)
}
const handleChange = (e) => {
console.log(e.target.files)
}
...
<form id="myFile" onSubmit={handleSubmit(onSubmit)}>
<input id="file1" type="file" {...register("file1")} onChange={handleChange}
style={{display:"none"}}/>
<label htmlFor="file1">
<Button variant="contained" component="span">
Choose file
</Button>
</label>
<input type="submit"/>
</form>
Is there any solution here?
You are forget to mention the type of the button
for Default material ui button type is
type="button"
Check this git Document
you should mention
type="submit"
So do like this
<Button type="submit" variant="contained" component="span">
Choose file
</Button>
You can try something like this:
import React, { useState } from 'react';
import { Button, TextField } from '#material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';
const Form: React.FC = () => {
const schema = object().shape({
username: string().required('username required'),
password: string().required('password required'),
});
const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
const onSubmit = (data: any) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="username"
error={!!errors.username}
label="Username"
helperText={errors.username ? errors.username.message : ''}
type="email"
inputRef={register}
fullWidth
/>
<TextField
name="password"
error={!!errors.password}
label="Password"
inputRef={register}
helperText={errors.password ? errors.password.message : ''}
type="password"
fullWidth
/>
<Button
color="secondary"
type="submit"
variant="contained"
fullWidth
>
Submit
</Button>
</form>
);
};
ref: How to use react-hook-form with ant design or material UI
Currently your submit event is controlled by the whole form element <form onSubmit={handleSubmit(onSubmit)}> but this is possible only when the form has a relevant submit button like <input type="submit"/> but when you use materail ui, MUI button doesnt distincts submit type even if mentioned.
So the solution is to move your onSubmit function at form to down the onClick event of your new MUI button.
The code that works is:
<Button onClick={handleSubmit(onSubmit)} type="submit" variant="contained" component="span"> Submit </Button>

getting values from <Field> onSubmit using React.js and redux.

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>
)
}

Categories