onSubmit function is not invoked even after clicking on submit button - javascript

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

Related

Modal closing right away

I am trying to add a modal to my page but it only stays open for a second and then closes again.
Here is my code:
Home.js
import './Home.css';
import React, {useState} from 'react';
import Modal from "./components/Modal";
function Home() {
const [openModal, setOpenModal] = useState(false);
return (
<div>
{console.log(openModal)}
<div className="App">
<header className="App-header">
<h1 className="App-name">iScore</h1>
</header>
</div>
<div className="Auth-form-container">
<form className="Auth-form">
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="form-group-both">
<div className="form-group mt-3">
<label>Email address: </label>
<input
type="email"
className="form-control mt-1"
placeholder="Enter email"
/>
</div>
</div>
<div className="form-group-pass">
<div className="form-group mt-3">
<label>Password: </label>
<input
type="password"
className="form-control mt-1"
placeholder="Enter password"
/>
</div>
</div>
<div className="popup">
<button className="submit"
>
Submit
</button>
</div>
{openModal && <Modal setOpenModals={setOpenModal}/>}
<p className="forgot-password text-right mt-2">
Forgot password?
</p>
<p>
Need an account?
</p>
<button className="sign-up" onClick={() => {
setOpenModal(true);
}}>Register
</button>
</div>
</form>
</div>
</div>
);
}
export default Home;
Modal.js
import "./Modal.css";
import {useState} from "react";
function Modal({ setOpenModals }) {
const handleChange = (event) => {
console.log("Checked: ", event.target.checked)
setAgreement(event.target.checked);
}
return(
<div className="modalBackground">
<div className="modalContainer">
<article>
<button className="Close" onClick={() => setOpenModals(false)}> × </button>
{/*<form>*/}
<div className="Auth-form-content">
<h3 className="Auth-form-title">Register</h3>
<div className="form-group mt-3">
<label>Email address: </label>
<input
type="email"
className="form-control mt-1"
placeholder="Enter email"
/>
</div>
<div className="form-group mt-3">
<label>Email address: </label>
<input
type="name"
className="form-control mt-1"
placeholder="Enter first name"
/>
</div>
<div className="form-group mt-3">
<label>Password: </label>
<input
type="password"
className="form-control mt-1"
placeholder="Enter password"
/>
</div>
<div className="form-group mt-3">
<label>Confirm Password: </label>
<input
type="password"
className="form-control mt-1"
placeholder="Enter password again"
/>
</div>
<div>
<input type="checkbox" name="terms" value="yes" onChange={handleChange}/>
<label htmlFor="terms"> I agree to the terms and conditions</label>
</div>
</div>
{/*</form>*/}
</article>
<footer>
<button disabled={!agreement} onClick={() => {handleSubmit();setOpenModals(false)}}>Register</button>
<button onClick={() => setOpenModals(false)} >Close</button>
</footer>
</div>
</div>
)
}
export default Modal
It seems that as soon as I press Register I can see in the console that openModal is set to True, but then immediately gets set back to false.
I am at a bit of a loss as to what to changes to try and make this work. From my perspective it should be doing it correctly.
Am I missing something here?
The issue is that in Modal.js in <button disabled={!agreement} onClick={() => {handleSubmit();setOpenModals(false)}}>Register</button> you use undeclared
agreement variable that cause Modal.js throw an error and do not render. You need pass agreement as prop or add a new state const [agreement, setAgreement] = useState(false) or remove disabled={!agreement} from a button in Modal.js
Edited
You have a form tag in Home.js and when you click Register button it opens the Modal AND submits a form. By default, a button has an innate type property of submit. When clicked, or activated inside a form, it will cause that form to submit (and trigger a corresponding submit event). This submit event cause Modal to close. Add type="button" to the Register button in Home.js.
at:
<button disabled={!agreement} onClick={() =>
{handleSubmit();setOpenModals(false)}}>Register</button>
You are calling setOpenModals false right after handleSubmit() which is causing immediate close of modal.
You need to close the modal in handleSubmit() function.

Html Form is not taking input on using handlechange event as use state hook

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

How can I resolve this React Modal Problem?

I am using react and I am a beginner in React. I am facing a problem while using React Modal.
It looks like modal is working but something is stopping it from working when I click on the button which opens Modal then this happens => The screen just blinks , The Modal opens and closes suddenly. I am using React useState Hook. No errors are reflected by the compiler in this code.
Here is my code :
import React from 'react'
import { useState } from 'react';
import Modal from 'react-modal'
import '../CSS/LoginSignup.css'
const LoginSignup = () => {
const [modalIsOpen , setIsOpen] = useState(false);
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
function afterOpenModal() {
if(!closeModal){
setIsOpen(true);
}
}
return (
<>
<div>
<div className="mainContainer">
<div className="maincontrol">
<div className="tagline">
<h1>Chat Free</h1>
<span><p>Connect with peoples and chat the way you like.</p></span>
</div>
<div className="login">
<form className="form">
<input type="text" id="login" className="inp1" name="login" placeholder="Email address or phone number" />
<input id="password" type="password" className="inp1" name="login" placeholder="Password" />
<button type="submit" className="btn" value="Log In">Log In</button>
Forgotten password?
<button type="SignUp" className="btn1" value="Sign Up" name="signUp" onClick={openModal}>Sign Up</button>
<Modal isOpen={modalIsOpen}
onAfterOpen={afterOpenModal}
onRequestClose={closeModal}
>
<div className="modal">
<div className="modal-content">
<h2>Sign Up!</h2>
<span className="close" onClick={closeModal} >×</span>
<form className='formsignup'>
<div className="fullname">
<div className="firtname">
<input type="text" placeholder="First Name" id="firstname" />
</div>
<div className="surname">
<input type="text" placeholder="Last Name" id="lastname" />
</div>
</div>
<div className="emailphone">
<input type="text" placeholder="Email or phone number" id="ephone"/>
</div>
<div className="password">
<input type="password" placeholder="Enter password" id="password"/>
</div>
<div className="dobmain">
<div className="date">
<label htmlFor="dob">Date of birth</label>
<input type="number" placeholder="Date" id="date"/>
</div>
<div className="month">
<input type="text" placeholder="Month" id="month"/>
</div>
<div className="year">
<input type="number" placeholder="Year" id="year"/>
</div>
</div>
<div className="gender">
<div className="male">
<label htmlFor="">Male</label>
<input type="radio" name="gender" id="male" />
</div>
<div className="female">
<label htmlFor="">Female</label>
<input type="radio" name="gender" id="male" />
</div>
<div className="other">
<label htmlFor="">Other</label>
<input type="radio" name="gender" id="male" />
</div>
</div>
<div className="button">
<button type="Register" className="btnR" value="Register" name="register">Sign Up</button>
</div>
</form>
</div>
</div>
</Modal>
</form>
</div>
</div>
</div>
</div>
</>
)
}
export default LoginSignup
It is the content on my console:
[HMR] Waiting for update signal from WDS...
webpackHotDevClient.js:138 src\Component\LoginSignup.js
Line 33:33: The href attribute requires a valid value to be accessible. Provide a valid, navigable address as the href value. If you cannot provide a valid href, but still need the element to resemble a link, use a button and change it with appropriate styles. Learn more: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md jsx-a11y/anchor-is-valid
printWarnings # webpackHotDevClient.js:138

Manage array from get request using useEffect and useState hooks in React

I need help in managing some values from a GET request that returns me an array of values from reading a file inside the server.
When loading the functional component I want send the request so I'm using useState and useEffect in my code like the following:
import { useHttpClient } from '../shared/hooks/http-hook';
...
const Settings = () => {
const { isLoading, error, sendRequest, clearError } = useHttpClient();
const [loadedSettings, setLoadedSettings] = useState([]);
useEffect(() => {
const fetchSettings = async () => {
try {
const responseData = await sendRequest(
'http://localhost/api/settings'
);
setLoadedSettings(responseData)
} catch (err) { }
};
fetchSettings();
}, []);
I need to do this to fill some inputs of my form with the values from the array I get from the request:
return (
<React.Fragment>
<ErrorModal error={error} onClear={clearError} />
{isLoading && <LoadingSpinner asOverlay />}
<form className="settings-form" onSubmit={settingsSubmitHandler}>
<div className="container">
<div className="row">
<div className="col">
<div className="form-group row">
<div className="col-sm-12">
<p>Database Connection:</p>
</div>
</div>
<div className="form-group row">
<div className="col-sm-12">
<Input
element="input"
id="hostname"
type="text"
title="HOSTNAME"
placeholder="HOST NAME"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
/>
</div>
</div>
<div className="form-group row">
<div className="col-sm-12">
<Input
element="input"
id="username"
type="text"
title="USERNAME"
placeholder="USERNAME"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
/>
</div>
</div>
<div className="form-group row">
<div className="col-sm-12">
<Input
element="input"
id="password"
type="password"
title="PASSWORD"
placeholder="PASSWORD"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
/>
</div>
</div>
...
If I console log:
loadedSettings.map(elem => {
console.log(elem)
}
It returns me all values from text file as expected.
How can I put every value in each input box?
Thanks
you can try to render the form input elements inside the map function
please let me know if this worked fine with you
return (
..
loadedSettings.map(elem=>(
<Input
element="input"
value={elem}
id="hostname"
type="text"
title="HOSTNAME"
placeholder="HOST NAME"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
/>
))
)
I think, you can just replace this section
<div className="col-sm-12">
<Input
element="input"
id="hostname"
type="text"
title="HOSTNAME"
placeholder="HOST NAME"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
/>
</div>;
with
{loadedSettings && loadedSettings.map((setting) => (
<div className="col-sm-12">
<Input
element="input"
id="hostname"
type="text"
title="HOSTNAME"
placeholder="HOST NAME"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
value={setting}
/>
</div>
)}
I solved with this {!isLoading && loadedSettings && ( and transformed array into an object so I can add in my input elements initialValue={loadedSettings.MYHOST} ecc..
{
"MYHOST": "value1",
"MYUSER": "value2",
....
....
}
Here the jsx code
return (
<React.Fragment>
<ErrorModal error={error} onClear={clearError} />
{isLoading && <LoadingSpinner asOverlay />}
{!isLoading && loadedSettings && (
<form className="settings-form" onSubmit={settingsSubmitHandler}>
<div className="container">
<div className="row">
<div className="col">
<div className="form-group row">
<div className="col-sm-12">
<p>Database Connection:</p>
</div>
</div>
<div className="form-group row">
<div className="col-sm-12">
<Input
element="input"
id="hostname"
type="text"
title="HOSTNAME"
placeholder="HOST NAME"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
initialValue={loadedSettings.MYHOST}
initialValid={true}
/>
</div>
</div>
<div className="form-group row">
<div className="col-sm-12">
<Input
element="input"
id="username"
type="text"
title="USERNAME"
placeholder="USERNAME"
validators={[VALIDATOR_REQUIRE()]}
errorText="Required."
onInput={inputHandler}
initialValue={loadedSettings.MYUSER}
initialValid={true}
/>
</div>
</div>
...
...

React onSubmit event not working

When I hit enter on the form, it does not trigger the onSubmit event. There are no errors. The other event, onBlur, does dispatch. The logForm function will eventually console.log a JSON string of all the form's fields, but I have not yet gotten that far. I am simply trying to trigger the onSubmit event on the form. Any help or explanation would be appreciated.
Here's the code:
import React from 'react'
export default function SignupForm() {
return (
<form onSubmit={logForm}>
<div className="form-group">
<label>
Name:
<input onBlur={logUpdate} className="form-control"
type="text" placeholder="Username"/>
</label>
</div>
<div className="form-group">
<label>
Email:
<input onBlur={logUpdate} className="form-control"
type="text" placeholder="johndoe#example.com"/>
</label>
</div>
<div className="form-group">
<label>
Password:
<input onBlur={logUpdate} className="form-control"
type="password" placeholder="Password"/>
</label>
</div>
<div className="form-group">
<label>
Confirm Password:
<input onBlur={logUpdate} className="form-control"
type="password" placeholder="Password"/>
</label>
</div>
</form>
)
}
function logForm(e) {
e.preventDefault()
const formInfo = new FormData(e.target)
console.log(formInfo)
}
function logUpdate(e) {
console.log(e.target.value)
}
What you can do is put an onKeyPressed event on your form controls like so
onKeyPress={this.onKeyPressed}
and then have a function catching the onKeyPressed
onKeyPressed: function (e) {
if (e.key === "Enter") {
logForm(e);
}
}
If you want Submit to work, add a button to your html section: (Credit to #TryingToImprove)
<div className="form-group">
<label>
<button className="btn btn-default" type="submit">submit form</button>
</label>
</div>

Categories

Resources