Clicking on react button asks me to leave site - reactjs

I am learning react and I have a component which as a 2 input fields and a button, at the moment, clicking on the button will display a message in console log, but when the button is clicked it displays a popup Leave site?, Changes that you made may not be saved.
this is my code in this component
import React, { useRef, useState, Component } from 'react'
import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import { signOut } from 'firebase/auth';
class InfoLgnTest extends Component {
render() {
this.state = {
user: null
}
return (
<div>
<div className="App">
<SignInWithEmailPassword />
</div>
</div>
)
}
}
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
return (
<>
<div className="form">
<form>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
<input type="submit" onClick={signIn}/>
</div>
</form>
</div>
</>
)
}
export default InfoLgnTest

This code has a form, by default form send data as a request on the same page, for resolve this:
Add onSubmit to form,
call preventDefault method from event
call the function signIn
Change <input type="submit" ... /> to <button type="submit">Send</button>
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
// new function to handle submit
const submitForm = (event) => {
event.preventDefault();
signIn();
}
return (
<>
<div className="form">
{/* Add onSubmit */}
<form onSubmit={submitForm}>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
{/* Change input to button */}
<button type="submit">Send</button>
</div>
</form>
</div>
</>
)
}

Related

useEffect not triggered on react hook form change

looking to use react hook form with useEffect to get changes in real time (as the user is filling out the form), is there a reason why useEffect isn't triggered here and if so is there a way to trigger it whenever the form data changes? example here is from https://remotestack.io/react-hook-form-set-update-form-values-with-useeffect-hook/
import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
export default function SimpleForm() {
const { register, handleSubmit, reset, formState } = useForm();
const [student, initStudent] = useState(null);
useEffect(() => {
setTimeout(
() =>
initStudent({
name: "Little Johnny",
email: "lil#johnny.com",
grade: "3rd",
}),
1200
);
}, []);
useEffect(() => {
console.log("updating.,..");
reset(student);
}, [reset, student]);
function onFormSubmit(dataRes) {
console.log(dataRes);
return false;
}
return (
<div>
<h2 className="mb-3">
React Initiate Form Values in useEffect Hook Example
</h2>
{student && (
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="form-group mb-3">
<label>Name</label>
<input
type="text"
name="name"
{...register("name")}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Email</label>
<input
type="email"
name="email"
{...register("email")}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Grade</label>
<input
type="text"
name="grade"
{...register("grade")}
className="form-control"
/>
</div>
<button type="submit" className="btn btn-dark">
Send
</button>
</form>
)}
{!student && (
<div className="text-center p-3">
<span className="spinner-border spinner-border-sm align-center"></span>
</div>
)}
</div>
);
}
You can use watch mode of react hook form to get every change.
const { register, handleSubmit, reset, formState, watch } = useForm();
useEffect(() => {
watch((value, { name, type }) => console.log(value, name, type));
}, [watch]);
Read more about watch mode form here
You need to trigger a state change whenever your input field value changes, and you do so using onClick event attribute like so:
import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
export default function SimpleForm() {
const { register, handleSubmit, reset, formState } = useForm();
const [student, initStudent] = useState(null);
useEffect(() => {
setTimeout(
() =>
initStudent({
name: "Little Johnny",
email: "lil#johnny.com",
grade: "3rd",
}),
1200
);
}, []);
useEffect(() => {
console.log("updating.,..");
reset(student);
}, [reset, student]);
function onFormSubmit(dataRes) {
console.log(dataRes);
return false;
}
return (
<div>
<h2 className="mb-3">
React Initiate Form Values in useEffect Hook Example
</h2>
{student && (
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="form-group mb-3">
<label>Name</label>
<input
type="text"
name="name"
{...register("name")}
onClick={(e)=>initStudent({...student, name: e.target.value})}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Email</label>
<input
type="email"
name="email"
{...register("email")}
onClick={(e)=>initStudent({...student, email: e.target.value})}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Grade</label>
<input
type="text"
name="grade"
{...register("grade")}
onClick={(e)=>initStudent({...student, grade: e.target.value})}
className="form-control"
/>
</div>
<button type="submit" className="btn btn-dark">
Send
</button>
</form>
)}
{!student && (
<div className="text-center p-3">
<span className="spinner-border spinner-border-sm align-center"></span>
</div>
)}
</div>
);
}

Using useEffect in react js to sent google rechaptha token

Hi i want implementation google rechapta using react, this is my react code
import { useForm } from 'react-hook-form';
import { useHistory } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import swal from 'sweetalert';
import ReCAPTCHA from "react-google-recaptcha";
const ContactForm = (props) => {
const {submitBtnClass } = props;
const { register, handleSubmit } = useForm();
const [token, setToken] = useState();
const history=useHistory();
const recaptchaRef = React.useRef();
function onChange(value) {
console.log("Captcha value:", value);
setToken(value);
}
useEffect(()=>{
document.getElementById("contact_tokenVal").value = token;
//const value = props.value
//setToken(value)
},[token]);
const onSubmit = data_api => {
axios
.post('http://localhost/erlanggastudio-rest-api/contact.php',data_api)
.then(res=>{
console.log(data_api);
history.push('/onepage-3');
swal(res.data.title, res.data.text, res.data.icon);
})
.catch(err => {
console.log(err);
});
};
return (
<form id="contact-form" onSubmit={handleSubmit(onSubmit)}>
<div className="row">
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_name" name="contact_name" placeholder="Nama" {...register('contact_name')} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_email" name="contact_email" placeholder="E-Mail" {...register('contact_email')} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_mobilephone" name="contact_mobilephone" placeholder="No Telepon" {...register('contact_mobilephone')} required/>
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_website" name="contact_website" placeholder="Website Anda" {...register('contact_website')} />
</div>
<div className="col-12 mb-30">
<textarea className="from-control" id="contact_message" name="contact_message" placeholder="Isi Pesan" {...register('contact_message')} required ></textarea>
</div>
<div className="col-12 mb-30">
<input className="from-control" type="hidden" id="contact_serverKey" name="contact_serverKey" value="6Lea50IhAAAAAAtfj-sElz7biY8WlDgrNwy7M7Tx" {...register('contact_serverKey')} />
<input className="from-control" type="hidden" id="contact_siteKey" name="contact_siteKey" value="6Lea50IhAAAAAEgdIvB6xUJ8KJCUyO-xKpPnA0fO" {...register('contact_siteKey')} />
<textarea className="from-control" id="contact_tokenVal" name="contact_tokenVal" defaultValue={token} {...register('contact_tokenVal')} />
</div>
<div className="col-md-6 mb-30">
<ReCAPTCHA
ref={recaptchaRef}
sitekey="6Lea50IhAAAAAEgdIvB6xUJ8KJCUyO-xKpPnA0fO"
onChange={onChange}
/>
</div>
</div>
<div className="btn-part">
<button className={submitBtnClass ? submitBtnClass : 'readon learn-more submit'} type="submit">Kirim</button>
</div>
</form>
);
}
export default ContactForm;
when the code running the view is like this :
i want to sent rechapta token using
<textarea className="from-control" id="contact_tokenVal" name="contact_tokenVal" defaultValue={token} {...register('contact_tokenVal')} />
after user klik rechapta, end will sent to server using axios, but i have some problem when sent the data to API Server using axion the rechapta token is blank like this screenshot :
my question is how to sent the rechapta token?, i'm using document.getElementById in useEffect, but still the value after sent is blank

event.preventDefault( ) is NOT working in React

Unable to get values in console!
What am I doing it incorrectly?
Attached below is the functional component of React
The Handler Functions
import React, { useState, useRef } from 'react';
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredName = nameInputRef.current.value;
console.log(enteredName);
};
return (
<form>
<div className="form-control" onSubmit={formSubmissionHandler}>
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
formSubmissionHandler should have on the form element rather than the div element.
return (
<form onSubmit={formSubmissionHandler}>
<div className="form-control">
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);

How to update a state, by taking reference of other state

I am working on a React project In my project I have two components one is Parent and another one is Child. In Parent component I have two buttons, one is Signup button and another one is Login Button. I imported Child component to Parent component, In Child component I have only Signup form is there. So I put state for Child component, that state logic contains initially Child component has to hide when I click Sigup button at that time only I have to show Child component up to here I have done. But here I was struck, When I click Signup button then I have hide both Signup and Login buttons, In output I have to show only Signup form.
This is Parent.js
import React, { useState } from 'react';
import Child from './Child/Child'
import './Parent.css';
const Parent = () => {
const [show, setShow] = useState(false)
const [showButtons, setShowButtons] = useState(true)
const showComponent = () => {
setShow(true)
}
const hideButtons = () => {
if(setShow(true)) {
setShowButtons(false)
}
}
return (
<div className='container'>
<div className='row'>
{showButtons &&
<div className='col-12' style={{display:"flex"}}>
<div className='col-6'>
<button className='btn btn-primary' onClick={() => {hideButtons(); showComponent()}}>Signup Form</button>
</div>
<div className='col-6'>
<button className='btn btn-danger'>Login Form</button>
</div>
</div>
}
</div>
<div className='row'>
<div className='col-12'>
{show && <Child></Child> }
</div>
</div>
</div>
)
}
export default Parent
This is Child.js
import React, { useState } from 'react';
import './Child.css';
const Child = () => {
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-6'>
<div className='signupForm'>
<form>
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" className="form-control" id="name" placeholder="Enter name"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" id="email" placeholder="Enter email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" id="password" placeholder="Enter password"></input>
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input type="password" className="form-control" id="confirmPassword" placeholder="Confirm password"></input>
</div>
<button type="submit" className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Child
If you think I am not clear with question please ask me where I am not clear
Do the following change in your parent.js then it will work
const hideButtons = () => {
setShowButtons(false);
};
Codesandbox here
You are currently testing your setShow function for truthiness, but you want to test its corresponding value. So change your hideButtons function to this:
const hideButtons = () => {
if(show) {
setShowButtons(false)
}
}

My onchange method is not working in react

import React, { Component } from 'react';
import TaskBar from './Task';
class Todo extends Component {
state = {
todo: ''
}
changeHandler = (event) => {
console.log(event.target.value);
}
render() {
return (
<React.Fragment>
<div className="card">
<h5 className="card-header">Todo</h5>
<div className="card-body">
<h5 className="card-title">Task you want to do</h5>
<form>
<input type="text" className="form-control" value={this.state.todo} name="todo" onChange={(event) => this.changeHandler(event)} />
</form>
</div>
<button className="btn btn-primary">Go somewhere</button>
</div>
</React.Fragment>
)
}
}
export default Todo;
In the above code i don't know why i couldn't make any change
2) I am using Bootstrap cdn in my public folder and i am using these classes here
You forgot to set state inside your onchange handler.
import React, { Component } from 'react';
import TaskBar from './Task';
class Todo extends Component {
state = {
todo: ''
}
changeHandler = (event) => {
console.log(event.target.value);
this.setState({todo: event.target.value}) //you forgot to do this//
}
render() {
return (
<React.Fragment>
<div className="card">
<h5 className="card-header">Todo</h5>
<div className="card-body">
<h5 className="card-title">Task you want to do</h5>
<form>
<input type="text" className="form-control" value={this.state.todo} name="todo" onChange={(event) => this.changeHandler(event)} />
</form>
</div>
<button className="btn btn-primary">Go somewhere</button>
</div>
</React.Fragment>
)
}
}
export default Todo;
Link to a codesandbox example - https://codesandbox.io/s/jydjj?module=/example.js
Also currently your onchange uses an arrow function which creates a new function on every hit which is considered bad practice so i would suggest you to do this instead.
<input type="text" className="form-control" value={this.state.todo} name="todo" onChange={this.changeHandler} />

Resources