Modal closing right away - javascript

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.

Related

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

Avoid go back page when press return inside field of form react

I would like to avoid, that when i fill a field in my form if i press return key, page go back to the previous page.
I would like that when i press return key, nothing happens or instead go to next field.
this is the code of my form:
Inside a react functional component in the return i have:
<Form
onSubmit={onSubmit}
render={({ handleSubmit, values }) => (
<form id='createForm' className="row mt-4" onSubmit={handleSubmit} >
<div className="col-md-1 mb-4">
<label htmlFor="inputDescription" className="form-label text-center">
<h5> Título </h5>
</label>
</div>
<div className="col-md-11">
<Field
className="form-control"
type="text"
name='title'
component="input"
// required
/>
</div>
<div className="col-md-1 mb-4">
<label htmlFor="inputResponse" className="form-label text-center" >
<h5> Texto </h5>
</label>
</div>
<div className="col-md-11">
<Field
className="form-control"
type="textarea"
name='text'
component="input"
// required
/>
</div>
<div className="col-md-1 mb-4">
<label htmlFor="link" className="form-label text-center" >
<h5> Enlace </h5>
</label>
</div>
<div className="col-md-5">
<Field
className="form-control"
type="link"
name="link"
component="input"
// required
/>
</div>
<div className="col-md-1 mt-1">
<label htmlFor="link_title" className="form-label text-center" >
<h5> Título Enlace </h5>
</label>
</div>
<div className="col-md-5">
<Field
className="form-control"
type="text"
name='link_title'
component="input"
// required
/>
</div>
<div className="buttons text-center mt-2">
<Volver className={"btn btn-outline-danger me-5 mb-3"} prevStep={prevStep} step={2} />
<button className="btn btn-outline-warning me-5 mb-3" onClick={(e) => (e.preventDefault(), openPreview(values))} >Vista Previa</button>
<SaveAndEdit className={"btn btn-outline-success me-5 mb-3"} idForm={'createForm'} text={'Guardar Respuesta'} />
<Cancelar className={"btn btn-outline-dark me-5 mb-3"} />
</div>
</form>
Form submits, by default, trigger a full page refresh, because this stuff dates back to before AJAX calls or dynamic content were possible.
One simple way to prevent this is to have your onSubmit function return false, which will prevent this behavior.
Another is to capture the submit event object and call .preventDefault() on it.
A third is to not use the form submit handler at all. Instead attach yout onSubmit function to the click event of the save button.
Remove onsubmit={handleSubmit} from this line:
<form id='createForm' className="row mt-4" onSubmit={handleSubmit}>
...and instead attach it to a click event wherever the user will be clicking to submit the form. If you were using a plain button this would be:
<button onClick={handleSubmit} idForm={'createForm'}>Guardar Respuesta</button>
...or you can handle that callback function from within your SaveAndEdit component just like any other callback property.

onSubmit function is not invoked even after clicking on submit button

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

React needs to be handled some if conditions

I have an issue with the if statement. The problem is I need to create a condition if the array has 2 object needs to be true if has 1 object it should be false. the objects are strings please check the code.
const { program } = useContext(ProgramContext);
const { authMethods } = program;
let loginComponent;
let claimComponent;
let insertRow;
let insertEnd;
if (authMethods) {
if (authMethods.indexOf('login') !== -1) {
loginComponent = (
<div className="col-md-6 d-flex">
<div className="card flex-grow-1 mb-md-0">
<div className="card-body">
<h3 className="card-title">Login</h3>
<form>
<div className="form-group">
<label htmlFor="login-id">User ID</label>
<input
id="login-id"
className="form-control"
placeholder="Please enter user ID"
/>
</div>
<div className="form-group">
<label htmlFor="login-password">Password</label>
<input
id="login-password"
type="password"
className="form-control"
placeholder="Password"
/>
<small className="form-text text-muted">
<ErrModal />
</small>
</div>
<div className="form-group">
<div className="form-check">
<span className="form-check-input input-check">
<span className="input-check__body">
<input
id="login-remember"
type="checkbox"
className="input-check__input"
/>
<span className="input-check__box" />
<Check9x7Svg className="input-check__icon" />
</span>
</span>
<label className="form-check-label" htmlFor="login-remember">
Remember Me
</label>
</div>
</div>
<button type="submit" className="btn btn-primary mt-2 mt-md-3 mt-lg-4">
Login
</button>
</form>
</div>
</div>
</div>
);
}
if (authMethods.indexOf('claim') !== -1) {
claimComponent = (
<div className="col-md-6 d-flex mt-4 mt-md-0">
<div className="card flex-grow-1 mb-0">
<div className="card-body">
<h3 className="card-title">Claim</h3>
<form>
<div className="form-group">
<label htmlFor="claim-code">Enter Claim Code</label>
<input
id="register-email"
type="text"
className="form-control"
placeholder="Claim Code"
/>
</div>
<button type="submit" className="btn btn-primary" style={{ marginTop: '186px' }}>
Claim
</button>
</form>
</div>
</div>
</div>
);
}
}
console.log(loginComponent);
console.log(claimComponent);
const rowComponent = (
<div className="container">
{insertRow}
{loginComponent}
{claimComponent}
{insertEnd}
</div>
);
Basically I want to add row class if there are 2 items in the array otherwise I don't need a row.
thank you
Your question is not clear so I'll chalk out a similar example:
import React from 'react'
const Component = () => {
const arr = ["foo", "bar"];
const rowClass = arr.length === 2 ? "row" : "";
return (
<div className={rowClass}>
This is an example
</div>
)
}
export default Component

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

Categories

Resources