I have prevented default behaviour of form on submit, but it still sending post request automatically to current url - reactjs

<form
className="login"
onSubmit={e => {
alert('hey getting called')
e.preventDefault()
this.authorizeUser(e)
}}
>
<input
type="text"
name="email"
onChange={e => this.handleInputChange(e)}
value={email}
className="login-input"
placeholder="Email Adress"
autoFocus
/>
<input
type="password"
name="password"
onChange={e => this.handleInputChange(e)}
value={password}
className="login-input"
placeholder="Password"
/>
<button
type="submit"
style={{height: '37px', float: 'left'}}
className="login-button"
>
Login
</button>
</form>
code is not reaching up to alert statement.
instead i see url changes to ->
http://localhost:3000/signin?email=testUSer%40abx.in&password=1234567 and page gets refreshed
This issue is happening after i updated react version from 16.9 to 17.0.0.
UPDATE
When i add the listener via add event listener inside componentDidMount() then suddenly it started working as expected!
still wonder why the onSubmit directly on form didn't work

Related

SMUI sveltekit Textfield always null on form submit

I've just started using SMUI and sveltekit and I'm running into an issue . . .
I'm using the Textfield component in a login form, and this doesn't work:
<form method="post">
<Textfield variant="outlined" bind:value={username} label="Username"></Textfield>
<Textfield type="password" variant="outlined" bind:value={password} label="Password">
<Button type="submit">Login</Button>
</form>
Which posts to a page with this code:
export const actions = {
default: async ({ cookies, request }) => {
const data = await request.formData()
const username = data.get('username')
const password = data.get('password')
}
}
username and password are both null on submit.
To make this work, I insert "shadow" hidden fields
<form method="post">
<Textfield variant="outlined" bind:value={username} label="Username"></Textfield>
<input type="hidden" name="username" value={username}>
<Textfield type="password" variant="outlined" bind:value={password} label="Password">
<input type="hidden" name="password" value={password}>
<Button type="submit">Login</Button>
</form>
And then I get values for username and password. I'm assuming I don't need to do this - what am I doing wrong?
Edit 2022-10-17
It was suggested that I add a "name" parameter to the textfields like so:
<Textfield variant="outlined" value="" name="username"></Textfield>
<Textfield type="password" variant="outlined" value="" name="password"></Textfield>
That also doesn't work - when the values come over for the form they are both null.
Other ideas?
You can specify the name of the nested input element like so:
<Textfield input$name="username" ... />
Form fields are only submitted if they have a name attribute. The bindings are completely irrelevant, you only need them if you want to use the values elsewhere in the code or component.

How to Navigate to another component in React

I'm using a functional component. I've tried using react router's useHistory. I'm trying to click a button and navigate to a new react component (screen or view).
function App() {
const history = useHistory();
function handleClick() {
history.push("/UserList");
}
return (
<div>
<form>
<br/>
<label>user name: </label>
<input type="email" name="email" onChange={e => setUserName(e.target.value)}/><br />
<br/>
<label>password:</label>
<input type="password" name="password" onChange={e => setPassword(e.target.value)} /><br />
<br />
<input type="submit" value="Sign In" onClick={() => handleCredentials}/>
</form>
<button onClick={handleClick}>User List</button>
</div>
);
Check what is you react router version. If its v6 then use useNavigation instead of useHistory. And there are changes to Switch,Route and more, but that you will find in docs.

Cannot read properties of undefined (reading 'updateProfile')

I am currently working on a project using react-redux framework where I have to create a login page and I have to save those login information....For that I have to catch the value...but I am stuck here for a while.
here is the code,
function Login() {
const [email, setEmail]=useState("");
const [password, setPassword]=useState("");
const [name, setName]=useState("");
const [profilePic, setProfilePic]=useState("");
const dispatch= useDispatch();
const logintoApp =(e) =>{
e.preventDefault();
auth.signInWithEmailAndPassword(email,password)
.then((userAuth)=>{
dispatch(login({
email:userAuth.user.email,
uid:userAuth.user.uid,
displayName:userAuth.user.displayName,
profileUrl:userAuth.user.photoURL,
}));
}).catch((error)=>alert(error));
};
const register =() =>{
if(!name){
return alert("Please enter a full name!")
}
auth.createUserWithEmailAndPassword(email,password)
.then((userAuth)=>{
userAuth.user.updateProfile({ <<====here is the problem=====>>
displayName:name,
photoURL:profilePic,
})
.then(()=>{
dispatch(
login({
email:userAuth.user.email,
uid:userAuth.user.uid,
displayName:name,
photoUrl:profilePic,
})
);
});
})
.catch((error)=>alert(error.message));
};
return (
<div className='login'>
<img
src="https://www.nicepng.com/png/detail/381-3813396_linkedin-ads-are-great-for-b2b-marketing-linkedin.png"
alt=""
/>
<form>
<input value={name} onChange={(e)=>setName(e.target.value)} placeholder="Full name (required if registering)" type="text"/>
<input value={profilePic} onChange={(e)=>setProfilePic(e.target.value)} placeholder="Profile pic URL (optional)" type="text"/>
<input value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="Email" type="email"/>
<input value={password} onChange={(e)=>setPassword(e.target.value)} placeholder="Password" type="password"/>
<button type='submit' onClick={logintoApp}>Sign In</button>
</form>
<p>Not a member? {' '}
<span className="login_register" onClick={register}>Register now</span>
</p>
</div>
)
}
export default Login
anyone have any idea how to fix this?
can you try to remove the form and type=submit from the button? what this type=submit is doing is that it submit the form and refresh it, so the data which you want to pass to the API became undefined
<input value={name} onChange={(e)=>setName(e.target.value)} placeholder="Full name (required if registering)" type="text"/>
<input value={profilePic} onChange={(e)=>setProfilePic(e.target.value)} placeholder="Profile pic URL (optional)" type="text"/>
<input value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="Email" type="email"/>
<input value={password} onChange={(e)=>setPassword(e.target.value)} placeholder="Password" type="password"/>
<button type='button' onClick={logintoApp}>Sign In</button>

react-hook-form can't see change value by click on button to reset input

Component with input and button to reset input TexInputComponent:
<input
type={type}
name={name}
ref={register}
/>
<button
type="button"
onClick={clearInput}>
Reset input
</button>
const clearInput = () => {
document.querySelector(`#${name}`).value = null;
};
I'm using TexInputComponent inside form in another component:
<TexInputComponent
name="title"
defaultValue={data?.title}
register={register({ required: 'Title is required.' })}
error={errors.title}
/>
Now when I click submit on form react-hook-form return me error e.g 'Title is required!'. When I writing something in TexInputComponent, then error disapear.
The problem is when I writing text and click button to reset input. The clearInput method is executed (this method changing value to null) Now should displaying error, but I thing the react hook form can't see value changing.
How I can fix it?
Your clearInput() doesn't work because you don't provide a unique id so it can't find the input element to reset. So change to this:
<input
id={name} // --> add this line to fix
type={type}
name={name}
ref={register}
/>
However there are other ways to easily reset the form without having to define your own reset method:
Use <input type='reset' /> to create a reset button that resets all fields in a form.
Use reset() function from useForm hook to reset a specific field:
const { register, reset } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First name</label>
<input type="text" name="firstName" ref={register} />
<label>Last name</label>
<input type="text" name="lastName" ref={register} />
<input type="submit" />
<button
type="button"
onClick={() => reset({ firstName: "default name" })}
>
Reset first name
</button>
</form>
);

semantic-ui-react: Does large dataset in Form.Select makes the Form slow?

I am having below form(inside modal) created using semantic-ui-react.
<Modal open={editBasicModal} size="small">
<Modal.Header>Your basic details</Modal.Header>
<Modal.Content scrolling>
<Form loading={isSubmitting}>
<Form.Group inline widths="equal">
<Form.Input
required
label="First Name"
fluid
type="text"
name="firstName"
value={values.firstName}
onChange={handleChange}
error={errors.firstName !== undefined}
/>
<Form.Input
required
label="Last Name"
fluid
type="text"
name="lastName"
value={values.lastName}
onChange={handleChange}
error={errors.lastName !== undefined}
/>
</Form.Group>
<Form.TextArea
label="Bio"
type="text"
name="bio"
value={values.bio}
onChange={handleChange}
rows={3}
error={errors.bio !== undefined}
/>
<Form.Select
label="Country"
name="location.country"
placeholder="Country"
value={values.location.country}
onChange={(e, { value }) => {
setFieldValue("location.country", value);
}}
options={this.state.allCountries}
/>
</Form>
</Modal.Content>
<Modal.Actions open={true}>
<Button type="submit" onClick={handleSubmit} >
Update
</Button>
</Modal.Actions>
</Modal>
The above code is from a component which uses Formik + yup.
this.state.allCountries is an array of 200+ records. Now this is making my form slow, the typing inside textarea and input are very slow.
As per my findings the large dataset in the Form.Select is causing the issue, because if i replace the options={this.state.allCountries} to options={[ { key: 1, value: "india", text: "india"} ]}, everything starts working fine. Or if I delete the Form.Selectthen also form works fine.
Few questions?
Is it a known issue?
what are the possible solutions?
I figured out that this is a problem with Form.Select. I changed it with select and everything worked smoothly then. Here is the updated code for select:
<Form.Field >
<label htmlFor="location.country">Country</label>
<select
name="location.country"
id="location.country"
value={values.location.country }
onChange={event => {
setFieldValue("location.country", event.target.value);
}}
>
<option key={0} value={undefined}>
-select-
</option>
{this.state.allCountries}
</select>
</Form.Field>
This renders similar(somewhat) select element with no slowness issue.
Hope it would help someone.

Resources