I am working on Reactjs and i am using nextjs framework,Right now i am trying to validate form using reactjs but i am not getting "alert" after click on submit button,How can i do this ? I tried with following code but not working
import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '@/styles/Home.module.css'
const inter = Inter({ subsets: ['latin'] })
import { useForm } from "react-hook-form";
export default function Home() {
const { handleSubmit } = useForm();
const checkauth = (data:any) => {
alert("Hello world");
};
return (
<div className="container">
<div className="screen">
<div className="screen__content">
<form className="login" onSubmit={handleSubmit(checkauth)}>
<div className="login__field">
<i className="login__icon fas fa-user" />
<input
type="text"
className="login__input"
placeholder="User name / Email"
/>
</div>
<div className="login__field">
<i className="login__icon fas fa-lock" />
<input
type="password"
className="login__input"
placeholder="Password"
/>
</div>
<button className="button login__submit">
<span className="button__text">Log In Now</span>
<i className="button__icon fas fa-chevron-right" />
</button>
</form>
</div>
</div>
</div>
);
}
CodePudding user response:
Try using event.preventDefault() in your checkAuth function. Also button should have type=“submit”.
CodePudding user response:
I tried to simulate this on react with register
and it's working. Find code below -
import React from 'react';
import { useForm } from 'react-hook-form';
export default function TempForm() {
const { handleSubmit, register } = useForm();
const checkauth = (data) => {
console.log(data);
alert('Hello world');
};
return (
<div className='container'>
<div className='screen'>
<div className='screen__content'>
<form className='login' onSubmit={handleSubmit(checkauth)}>
<div className='login__field'>
<i className='login__icon fas fa-user' />
<input
type='text'
className='login__input'
placeholder='User name / Email'
{...register('username')}
/>
</div>
<div className='login__field'>
<i className='login__icon fas fa-lock' />
<input
type='password'
className='login__input'
placeholder='Password'
{...register('password')}
/>
</div>
<button className='button login__submit'>
<span className='button__text'>Log In Now</span>
<i className='button__icon fas fa-chevron-right' />
</button>
</form>
</div>
</div>
</div>
);
}