"useHistory is not defined" in react js create-react-app - reactjs

I am trying to build an easy password protected page with an hardcoded password and a random token generated, However I am getting multiple errors, the most prominent one being "userHistory" is not defined, there area host of other bugs but I intend to solve them as I am new to react, anybody here care to help? Please find below my code
import React, {useState} from 'react';
function Singmein () {
const [passwordInput, setPasswordInput] = useState('');
const history = useHistory();
function handlePasswordChange(e){
setPasswordInput(e.target.value);
}
const handleLoginSubmit = (e) => {
e.preventDefault();
let hardcodedCred = {
password: 'password123'
}
if ((passwordInput == hardcodedCred.password)) {
//combination is good. Log them in.
//this token can be anything. You can use random.org to generate a random string;
const token = '123456abcdef';
sessionStorage.setItem('auth-token', token);
//go to www.website.com/todo
history.push('/signin');
} else {
//bad combination
alert('wrong email or password combination');
}
}
}
class signin extends React.Component{
render () {
return (
<div className="d-flex flex-column flex-root">
<div className="login login-4 login-signin-on d-flex flex-row-fluid" id="kt_login">
<div className="d-flex flex-center flex-row-fluid bgi-size-cover bgi-position-top bgi-no-repeat" style={{backgroundColor: 'white'}}>
<div className="login-form p-7 position-relative overflow-hidden">
<div className="d-flex flex-center">
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</div>
<div className="card card-board" style={{backgroundColor: '#F0F1F4', width: '100%'}}>
<div className="card-body">
<div className="mb-10">
<h3 className="font-weight-bold">This website is password protected</h3>
</div>
<form className="form" autoComplete="off" id="kt_login_signin_form" onSubmit={handleLoginSubmit}>
<div className="form-group mb-5">
<label htmlFor="username">Enter Unique Password</label>
<input className="form-control h-auto form-control-solid py-4 px-8"
style={{backgroundColor: 'white'}}
type="password"
placeholder="Password"
name="password"
value={passwordInput}
onChange={handlePasswordChange} />
</div>
Enter
</form>
</div>
</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</div>
</div>
</div>
</div>
);
}
};
export default signin;

You need to import { useHistory } from 'react-router-dom';

You have to import react-router-dom like this:
import {useHistory} from "react-router-dom";
So, your full code will look like this:
import React, {useState} from 'react';
import {useHistory} from "react-router-dom";
function Singmein () {
const [passwordInput, setPasswordInput] = useState('');
const history = useHistory();
...
}

Related

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

Problems with react for animation

i have the login page without the js animation
after i add the animation code i dont get a render in the login page,
i use this to add the annimation
const signUpButton = document.getElementById('signUp')
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});
Here's the code:
import React from 'react';
const Loginpart = () => {
return (
<div>
<section className="position-relative pb-0">
<div className="gen-login-page-background" ></div>
<div className="container" id="container">
<div className="form-container sign-up-container">
<form action="#">
<h1 >Create Account</h1>
<span>or use your email for registration</span>
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
<button>Sign Up</button>
</form>
</div>
<div className="form-container sign-in-container">
<form action="#">
<h1 >Sign in</h1>
<span>or use your account</span>
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
Forgot your password?
<button>Sign In</button>
</form>
</div>
<div className="overlay-container">
<div className="overlay">
<div className="overlay-panel overlay-left">
<h1>Welcome Back!</h1>
<p>To keep connected with us please login with your personal info</p>
<button className="ghost" id="signIn">Sign In</button>
</div>
<div className="overlay-panel overlay-right">
<h1>Hello, Friend!</h1>
<p>Enter your personal details and start journey with us</p>
<button className="ghost" id="signUp">Sign Up</button>
</div>
</div>
</div>
</div>
</section>
</div>
);
};
export default Loginpart;
this is the code for animation :
const signUpButton = document.getElementById('signUp')
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});
Chances are, when you start the handler functions, the Loginpart component still hasn't rendered.
Check the constants if they are undefined.
Perhaps this approach is more suitable for you with react
import React, {useState} from 'react'
const Component=()=>{
const [anime, setAnime] = useState(false)
function handleAnimation(){
setAnime(!anime)
}
<div id='container' className={`container ${anime&&'right-panel-active'}`}>
<button onClick={handleAnimation}></button>
</div>
}
export default Component
There are actually several ways to do this, css-in-js, or even with pure javascript, but you would have to ensure that the component is already assembled.

login problem and onSubmit problem in react js

I have a problem with login ( i need to check email and pass ) its only check email
my second problem is with onSubmit in form doesn't work!
`import React, {useEffect, useState} from 'react';
import loginImg from '../../assets/images/login.svg';
import {Link} from "react-router-dom";
const Login = () => {
const [email,setEmail] = useState("");
const [password,setPassword] = useState("");
const [isLogin,setIsLogin]=useState(1);
const TOKEN_KEY = 'jwt';
const handleLogin=()=>{
if (email === "bardia#test.com" && password === "1212"){
setIsLogin(1);
} else {
setIsLogin(0)
}
}
useEffect(()=>{
if (isLogin === 1){
localStorage.setItem(TOKEN_KEY, 'TestLogin');
} else {
localStorage.removeItem(TOKEN_KEY);
}
})
return (
<div className="container-fluid">
<form onSubmit={handleLogin} className="row">
<div className="col-md-6 col-sm-12 text-center align-self-center">
<div>
<p className="h1">ورود</p>
<div className="col-sm-12 col-md-4 py-4 mx-auto">
<input className="form-control" required autoFocus type="email" onChange={e => setEmail(e.target.value)} placeholder=" ایمیل خود را وارد کنید"/>
</div>
<div className="col-sm-12 col-md-4 pb-4 mx-auto">
<input className="form-control" required type="password" onChange={e => setPassword(e.target.value)} placeholder=" رمز عبور خود را وارد کنید"/>
</div>
<Link to="/dashboard" className="btn btn-primary" > ورود</Link>
</div>
</div>
<div className="col-md-6 col-sm-12">
<img src={loginImg}/>
</div>
</form>
</div>
);
};`
I hope you are doing well,In you code, Login component not triggered handleLogin method because of you don't written button type of submit. That reason not call handleLogin method in login component. so you can replace to button type submit.
syntax:
<input type="submit" value="Login">
I hope you are understand after this read.

e.preventDefault() not working in my react app which is causing unnessary redirect

Hi I am trying to create a react-redux form and my e.preventDefault() is not working which i causing a redirect everytime I press an enter key.
Could someone look in my code and tell me where am I going wrong:
I am having an input field and when I am giving an e.preventDefault(), but for some reason its redirecting.
import React, { useState } from "react";
import { useDispatch } from "react-redux";
function InputField() {
let [task, setTask] = useState("");
const dispatch = useDispatch();
let onTaskAdd = (e) => {
setTask(e.target.value);
};
let addTaskinTaskManager = () => {
dispatch({ type: "ADD_TASK", payload: task });
setTask("");
};
return (
<div className="container-fluid mt-5">
<div className="row justify-content-center">
<div className="col-md-6">
<form>
<div className="form-group row">
<label className="col-md-2 col-form-label">Task:</label>
<div className="col-md-10">
<input
type="text"
id="task"
name="task"
className="form-control"
placeholder="eg, singing"
value={task}
onChange={(e) => {
e.preventDefault();
e.stopPropagation();
onTaskAdd(e);
}}
/>
</div>
</div>
</form>
</div>
<div className="col-md-2">
<button
type="button"
onClick={addTaskinTaskManager}
className="btn btn-primary"
>
Add Task
</button>
</div>
</div>
</div>
);
}
export default InputField;

Change auth state from custom component while using #aws-amplify with react

I am trying to integrate Amplify Auth with a React application.
I am using AmplifyAuthenticator from #aws-amplify/ui-react package to customize the auth flow.
Though I can use AmplifySignIn component and customize it, I want to create a totally custom instead of AmplifySignIn.
Following is what my custom component looks like:
import React from 'react';
import { Auth } from 'aws-amplify';
import { useForm } from "react-hook-form";
export default function CustomSignIn(props){
const { register, reset, errors, handleSubmit } = useForm();
const onSubmit = async data => {
await Auth.signIn(data.username, data.password);
};
return(
<form className="mt-5" onSubmit={handleSubmit(onSubmit)} slot={props.slot}>
<h4>Login</h4>
<p>Need an account? <span>Create an account</span></p>
<div className="form-group">
<label>Email address</label>
<input type="username" name="username" className="form-control" ref={register({required: true})}/>
</div>
<div className="form-group">
<label>Password</label>
<input type="password" name="password" className="form-control" ref={register({required: true})}/>
</div>
<button type="submit" class="btn btn-primary btn-block">Continue</button>
</form>
);
}
Following is how I am trying to manage auth state:
import React, {useEffect} from 'react';
import { AmplifyAuthenticator } from '#aws-amplify/ui-react';
import '../styles/App.scss';
import { AuthState, onAuthUIStateChange } from '#aws-amplify/ui-components';
import ProtectedRoutes from './ProtectedRoutes';
import logo from '../assets/logo.svg';
import CustomSignIn from '../modules/auth/CustomSignIn';
function App() {
const [authState, setAuthState] = React.useState();
const [user, setUser] = React.useState();
useEffect(() => {
return onAuthUIStateChange((nextAuthState, authData) => {
setAuthState(nextAuthState);
setUser(authData)
});
}, []);
return ( authState === AuthState.SignedIn && user )
?
(
<ProtectedRoutes />
)
:
(
<div className="container-fluid container-fluid--auth">
<div className="row">
<div className="col-md-8">
<div className="row">
<div className="col-12 py-3">
<img className="logo" src={logo} alt="logo" />
</div>
</div>
<div className="row">
<div className="col-md-4 offset-md-4">
<AmplifyAuthenticator>
<CustomSignIn slot="sign-in" />
</AmplifyAuthenticator>
</div>
</div>
</div>
<div className="col-md-4 col--auth-sidebar">
</div>
</div>
</div>
);
}
export default App;
The thing is, how do I take the user to the Sign Up page when the user clicks on the "Create an account" button on the Sign In page?

Resources