How to use react-intl-tel-input in ReactJS - javascript

Hello I have started learning ReactJS from past 1 months and from last 1 week i stuck with a problem. I am using React with Firebase Phone Authentication. I want to use react-intl-tel-input for taking Phone input but when i install the package and write the code while writing i don't understand how to use the code in right way and getting this type of error × TypeError: Cannot read properties of null (reading 'phoneNumber'). or some times its give me this error × TypeError: Cannot read properties of null (reading 'e') I don't want that user have to type there country code manually with phone Number I want that user can simply select there country and type there phone number
can Any one Please Help me i stuck in this from more than 1 week tried different npm packages also try to use jQuery but nothing work for me.
this is my code ( App.js )
import React from 'react'
import firebase from './firebase'
import IntlTelInput from 'react-intl-tel-input';
import 'react-intl-tel-input/dist/main.css';
class App extends React.Component {
handleChange = (e) =>{
const {name, value } = e.target
this.setState({
[name]: value
})
}
configureCaptcha = () =>{
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
this.onSignInSubmit();
console.log("Recaptca varified")
},
defaultCountry: "IN"
});
}
onSignInSubmit = (e) => {
e.preventDefault()
this.configureCaptcha()
const phoneNumber = "+91" + this.state.mobile
console.log(phoneNumber)
const appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
console.log("OTP has been sent")
alert("OTP has been sent")
}).catch((error) => {
// Error; SMS not sent
// ...
console.log("SMS not sent")
alert("SMS not sent")
});
}
onSubmitOTP = (e) =>{
e.preventDefault()
const code = this.state.otp
console.log(code)
window.confirmationResult.confirm(code).then((result) => {
// User signed in successfully.
const user = result.user;
console.log(JSON.stringify(user))
alert("User is verified")
// ...
}).catch((error) => {
// User couldn't sign in (bad verification code?)
// ...
});
}
render() {
return (
<div>
<h2>Login Form</h2>
<form onSubmit={this.onSignInSubmit}>
<div id="sign-in-button"></div>
<IntlTelInput
containerClassName="intl-tel-input"
inputClassName="form-control"
placeholder="Enter Your Number"
value={this.state.phoneNumber}
onPhoneNumberChange={this.handlePhoneChange} />
{/* <input type="number" name="mobile" placeholder="Mobile number" required onChange={this.handleChange}/> */}
<button type="submit">Submit</button>
</form>
<h2>Enter OTP</h2>
<form onSubmit={this.onSubmitOTP}>
<input type="number" name="otp" placeholder="OTP Number" required onChange={this.handleChange}/>
<button type="submit">Submit</button>
</form>
</div>
)
}
}
export default App

This library does not return a component, am pasting my component.
phoneInput.js
import React, { useEffect, useState } from 'react';
import intlTelInput from 'intl-tel-input';
import clsx from 'clsx';
import 'intl-tel-input/build/css/intlTelInput.css';
export const PhoneInput=({disabled,...rest})=>{
//rest may include-name, onChange, etc
const [options,toggleOptions]=useState({
allowDropdown:true,
autoHideDialCode:false,
initialCountry: "auto",
separateDialCode:true,
nationalMode:false,
hadInitialPlaceholder:true,
utilsScript: process.env.REACT_APP_PHONE_UTIL_SCRIPT,
geoIpLookup: async function(callback) {
await fetch(process.env.REACT_APP_GEOIP_SERVICE)
.then(res=>res.json())
.then(({country})=>{
callback(country)
})},
customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
return "e.g. " + selectedCountryPlaceholder;
},
})
useEffect(()=>{
const input = document.querySelector("#signup-phone");
if(!input) return;
const iti=intlTelInput(input, {
...options
});
return()=>{
iti.destroy();
}
},[])
useEffect(()=>{
toggleOptions(o=>({
...o,
allowDropdown:!disabled
//disable dropdown when disable flag is set
}));
},[disabled])
return(
<input
disabled={disabled}
type="tel"
id="signup-phone"
{...rest}
/>
)
}
Utilised in
signup.js
<PhoneInput
name="phone_no"
onChange={handleChange}
disabled={loading}
error={errors['phone_no']}
/>

Related

How to verify a react-google-recaptcha v2 using jest while testing a React-Typescript App?

So basically I've a Login form with two input fields (password, email) and a react-google-recaptcha. My use case is simple. Test if the submit button is disabled if the input fields are empty and recaptcha is not verified. Enable it only when input fields contain data and recaptcha is verified.
Below is the code that I wrote and I know I did something wrong with recaptcha verification in test file.
I've gone through existing answers in Stack Overflow for example this but facing problem implementing the same.
Login.tsx
import React, { useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
const Login = () => {
const [creds, setCreds] = useState({
email: "",
pw: "",
});
const [isCaptchaVerified, setIsCaptchaVerified] = useState(false);
const handleCaptchaChange = (value): void => {
if (value !== null) setIsCaptchaVerified(true);
else setIsCaptchaVerified(false);
};
return (
<div>
<input
data-testid="email-testid"
type="email"
name="email"
value={creds.email}
onChange={(e) => {
setCreds({
email: e.target.value,
pw: creds.pw,
});
}}
/>
<input
data-testid="pw-testid"
type="password"
name="password"
value={creds.pw}
onChange={(e) => {
setCreds({
pw: e.target.value,
email: creds.email,
});
}}
/>
<ReCAPTCHA
data-testid="login-recaptcha"
sitekey={siteKey}
onChange={handleCaptchaChange}
/>
<button data-testid="submit-testid" disabled={!isCaptchaVerified || !creds.pw ||
!creds.email}>
Submit
</button>
</div>
);
};
export default Login;
Login.test.tsx
test("test if button is disabled untill captcha is verified",()=> {
const loginRecaptcha = screen.findByTestId('login-recaptcha');
const emailField = screen.findByTestId('email-testid');
const pwField = screen.findByTestId('pw-testid');
const submitButton = screen.findByTestId('submit-testid');
expect(submitButton).toBeDisabled();
fireEvent.change(emailField, { target: { value: "user#test.com" } });
fireEvent.change(pwField, { target: { value: "user#1234" } });
fireEvent.click(loginRecaptcha);
expect(submitButton).not.toBeDisabled();
})

FirebaseError: Firebase: Error (auth/user-token-expired) [duplicate]

This question already has an answer here:
firebase: admin.auth().updateUser() causes auth/user-token-expired
(1 answer)
Closed 8 months ago.
I have created a new form after creating a user with phone number authentication(in firebase), But an error keeps on coming after submitting FirebaseError: Firebase: Error (auth/user-token-expired)
The Error is Comming in this code
//This Component is used to store the Name ,Phone Number Of new User Which have Registered in SignUp With Number
import "./Auth.scss";
import React, { useState } from "react";
import { updateProfile, updateEmail } from "firebase/auth";
import { auth } from "../../firebase/config";
import { useNavigate, useLocation } from "react-router";
import usePhoneSignUp from "../../hooks/usePhoneSignUp";
import { update } from "lodash";
const SaveUserDetails = () => {
//code to extract userType after navigating from SignUpWithNumber page
const { state } = useLocation();
const userType = state.userType;
console.log(userType);
// .......
const {
signUp,
error: signupError,
isPending: signupIsPending,
} = usePhoneSignUp();
const [name, setname] = useState();
const [email, setemail] = useState();
const navigate = useNavigate();
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
switch (name) {
case "displayname":
setname(value);
break;
case "email":
setemail(value);
break;
default:
break;
}
};
const updateEmailUser = () => {
updateEmail(auth.currentUser, email)
.then(() => {
// Email updated!
// ...
console.log("email Updated");
})
.catch((error) => {
// An error occurred
console.log("email Updated");
// ...
console.log(error);
});
};
const updateUserProfile = () => {
updateProfile(auth.currentUser, {
displayName: name,
})
.then(() => {
console.log("profile Updated" + name + " " + email);
})
.catch((error) => {
console.log(error + "In update profile");
});
updateEmailUser();
};
const handleSubmit = () => {
// updateEmailUser();
updateUserProfile();
signUp(name, userType, email);
let path =
userType === "salonOwner" ? "/addBuisnessDetails" : "/salonsNearby";
if (signupError) {
console.log(signupError.message);
}
return navigate(path, { replace: true });
};
//query function for saloon
return (
<>
<div className="form-wrapper ">
<div id="register-form">
<p className="login-title register-title">Complete Your Profile</p>
<div className="login-hr" />
<form onSubmit={handleSubmit}>
<div className="form-group login-sj">
<label htmlFor="exampleInputName1">Name:</label>
<input
type="text"
className="form-control"
id="exampleInputName1"
aria-describedby="emailHelp"
placeholder="Your Name"
name="displayname"
onChange={handleChange}
/>
</div>
<div className="form-group login-sj">
<label htmlFor="exampleInputEmail2">Email address</label>
<input
type="email"
className="form-control"
id="exampleInputEmail2"
aria-describedby="emailHelp"
placeholder="Enter email"
name="email"
onChange={handleChange}
/>
</div>
{/* <div className="form-group login-sj">
<label htmlFor="exampleInputPassword1"></label>
<input
type="password"
className="form-control"
id="exampleInputPassword2"
placeholder="Password"
value={userPassword}
onChange={(e) => setUserPassword(e.target.value)}
/>
</div> */}
{signupIsPending ? (
<>
<button
type="submit"
className="btn-auth-sj btn btn-primary"
disabled
>
Save Details
</button>
</>
) : (
<>
<button type="submit" className="btn-auth-sj btn btn-primary">
Save Details
</button>
</>
)}
</form>
</div>
</div>
</>
);
};
export default SaveUserDetails;
The part where error is Comming
.catch((error) => {
console.log(error + "In update profile");
});
Due to this my displayName Is not getting saved and after submitting user is getting logged out automatically.
I also asked this question previously and implemented it as answered Is their any function signupwithphonenumber in firebase just like signupwithemailandpassword? (for web) I want to make user register with his creds
Thanks In advance
Okay So the problem got resolved gust by wrapping updateProfile function(one provided by firebase) into
auth.currentUser.reload().then(() => { /* update profile function here */ })
Or In my case :-
const updateUserProfile = () => {
auth.currentUser.reload().then(() => {
updateProfile(auth.currentUser, {
displayName: name,
})
.then(() => {
console.log("profile Updated" + name + " " + email);
})
.catch((error) => {
console.log(error + "In update profile");
});
updateEmailUser();
});
};

While implementing react-intl-tel-input in my react JS it give me errors

Hello I have started learning ReactJS and from last 1 week i stuck with a problem. I am using React with Firebase Phone Authentication. I want to use react-intl-tel-input for taking Phone input. I have installed the npm package and write the code as told in documentation. after running the code it takes the input correctly but after clicking on verify it say this number is not register but this number work perfectly with tag but not with this
please have a look on my code
import React from 'react'
import firebase from './firebase'
import 'firebase/auth';
import "./App.css";
import { getDatabase, ref, child, get } from "firebase/database";
import IntlTelInput from 'react-intl-tel-input';
import 'react-intl-tel-input/dist/main.css';
class Login extends React.Component {
state = {};
handlePhoneChange = (status, phoneNumber, country) => {
console.log({ phoneNumber });
this.setState({ phoneNumber });
};
handleChange = (e) => {
console.log (e)
const { name, value } = e.target
this.setState({
[name]: value
})
console.log (value)
this.setState({ phoneNumber: value }, () => {
console.log(this.state.phoneNumber);
});
}
configureCaptcha = () =>{
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
this.onSignInSubmit();
console.log("Recaptca varified")
},
// defaultCountry: "IN"
}
);
}
onSignInSubmit = (e) => {
e.preventDefault()
this.configureCaptcha()
const phoneNumber = this.state.mobile
console.log(phoneNumber)
const appVerifier = window.recaptchaVerifier;
const dbRef = ref(getDatabase());
get(child(dbRef, `Users/${phoneNumber}`)).then((snapshot) => {
if (snapshot.exists()) {
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
window.confirmationResult = confirmationResult;
alert('An OTP has been sent to your registered mobile number')
localStorage.setItem("Phone_No", phoneNumber)
console.log(localStorage.getItem('Phone_No'));
}).catch((error) => {
console.error(error);
alert("Oops! Some error occured. Please try again.")
});
}
else {
alert('Sorry, this mobile number is not registered with us. Please use your registered mobile number.');
}
})
}
onSubmitOTP = (e) => {
e.preventDefault()
const code = this.state.otp
console.log(code)
window.confirmationResult.confirm(code).then((result) => {
// User signed in successfully.
const Users = result.user;
console.log(JSON.stringify(Users))
this.props.history.push("/home");
}).catch((error) => {
alert("You have entered wrong code")
});
}
render() {
return (
<>
<main>
<div className="img">
<img src="./55k-logo.png" alt="Company Logo" style={{ height: "80px", width: "200px" }} />
<br />
</div>
<fieldset>
<div className="Main-header">
<h1>Sign-In</h1>
<p>Limtless Water. From Unlimited Air.</p>
<form onSubmit={this.onSignInSubmit}>
<div id="sign-in-button"></div>
<label>Mobile Number</label> <br />
<IntlTelInput
containerClassName="intl-tel-input"
inputClassName="form-control"
name="mobile"
placeholder="Enter Your Number"
input
type="tel"
value={this.state.phoneNumber}
onPhoneNumberChange={this.handlePhoneChange}
/>
{/* <input type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange} /> */}
<div className="buttons">
<button type="submit">Verify</button>
</div>
</form>
<div>
<form onSubmit={this.onSubmitOTP}>
<label >Code</label> <br />
<input type="text" name="otp" placeholder="Enter six digit code" required onChange={this.handleChange} />
<div className="buttons" >
<button type="submit">Continue</button>
</div>
</form>
</div>
</div>
</fieldset>
</main>
</>
)
}
}
export default Login;
after running the code i got this message but my number is registered
But my code work perfectly with this
<input type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange} /> but i don't want to take input with normal input tag because here user have to type country code manually

How to integrate react-intl-tel-input-v2

While using react-intl-tel-input-v2 I was getting this error:-× TypeError: Cannot read properties of null (reading 'e') I have install the react-intl-tel-input-v2 from npm Try many things but nothing work if anyone know the solution please help Even if you know any other npm package which help me please suggest
I was getting the error in this part:-
handleChange = (e) => { const { name, value } = e.target this.setState({ [name]: value
This is my code
import React from 'react'
import firebase from './firebase'
import 'firebase/auth';
import "./App.css";
import { getDatabase, ref, child, get } from "firebase/database";
// import PhoneInput from 'react-phone-number-input'
// import $ from 'jquery';
// import intlTelInputUtils from 'jquery';
import ReactIntlTelInput from 'react-intl-tel-input-v2';
import 'intl-tel-input/build/css/intlTelInput.css';
class Login extends React.Component {
handleChange = (e) => {
const { name, value } = e.target
this.setState({
[name]: value
})
this.setState({ phoneNumber: value }, () => {
console.log(this.state.phoneNumber);
});
}
configureCaptcha = () =>{
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
this.onSignInSubmit();
console.log("Recaptca varified")
},
defaultCountry: "IN"
}
);
}
onSignInSubmit = (e) => {
e.preventDefault()
this.configureCaptcha()
const phoneNumber = this.state.mobile
console.log(phoneNumber)
const appVerifier = window.recaptchaVerifier;
const dbRef = ref(getDatabase());
get(child(dbRef, `Users/${phoneNumber}`)).then((snapshot) => {
if (snapshot.exists()) {
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
alert('An OTP has been sent to your registered mobile number')
localStorage.setItem("Phone_No", phoneNumber)
console.log(localStorage.getItem('Phone_No'));
}).catch((error) => {
console.error(error);
alert("Oops! Some error occured. Please try again.")
});
}
else {
alert('Sorry, this mobile number is not registered with us. Please use your registered mobile number.');
}
})
}
onSubmitOTP = (e) => {
e.preventDefault()
const code = this.state.otp
console.log(code)
window.confirmationResult.confirm(code).then((result) => {
// User signed in successfully.
const Users = result.user;
console.log(JSON.stringify(Users))
this.props.history.push("/home");
}).catch((error) => {
alert("You have entered wrong code")
});
}
render() {
return (
<div className="Main-header">
<img src="./55k-logo.png" alt="Company Logo" style={{ height: "80px", width: "200px" }} />
<br />
<div>
<h2>Login Form</h2>
<p>Limtless Water. From Unlimited Air.</p>
<form onSubmit={this.onSignInSubmit}>
<div id="sign-in-button"></div>
{/* <PhoneInput */}
<label>Mobile Number</label> <br />
{/* for="phoneNumber" */}
<ReactIntlTelInput
type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange}
value={this.state.value}
// onChange={this.handleChange}
/>
{/* <input type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange} /> */}
<div className="buttons">
<button type="submit">Submit</button>
</div>
</form>
</div>
<div>
<form onSubmit={this.onSubmitOTP}>
<label >Code</label> <br />
{/* for="code" */}
<input type="number" name="otp" placeholder="Enter The 6 Digit OTP" required onChange={this.handleChange} />
<div className="buttons" >
<button type="submit">Submit</button>
</div>
</form>
</div>
</div>
)
}
}
export default Login;

How to display the state on the same page when clicked Submit button in react

I have made a form in react which takes input from the user and stores it in the state. Now, I want to display the state values when the user clicks Submit button in an input field just below the submit button in React.
Im new to react.
You have to make an object (E.g. Credentials) and when someone clicks the button, credential takes the props of the state like this:
App.js
//import code....
import Form from './Form.js'
//class app code.....
//in the render method:
render() {
return (
<Form />
)
}
Form.js
// import code ....
state = {
firstName: '', // or what you want
lastName: '', // or what you want
email: '', // or what you want
send: false,
}
//handleChange function
const handleChange = (event) => {
const {name, value} = event.target
this.setState({
[name]: value
})
}
//handleClick function
const handleClick = () => {
this.setState({send: true})
}
In the Render method
render() {
return (
<div>
<input name='firstName' onChange={handleChange} />
<input name='lastName' onChange={handleChange} />
<input name='email' onChange={handleChange}/>
<button onClick={handleClick}>Send</button>
{send &&
<Credentials
firstName={this.state.firstName}
lastName={this.state.lastName}
email={this.state.email}
/>
}
</div>
)
}
export default Form // or your file's name
In the Credential.js
//import code...
const Credentials = ({firstName, lastName, email}) => {
return (
<h2>firstName is: {firstName}</h2>
<h4>lastName is: {lastName}</h4>
<p>email is: {email}</p>
)
}
export default Credentials
In React you can use 'useState' to initiate a number or any kind of input. Then set that number when the user clicks on a button.
import React, { useState } from "react";
function App() {
const [number, setNumber] = useState();
let typedNumber = 0;
const btnHandler = (e) => {
e.preventDefault();
setNumber(typedNumber);
};
return (
<div>
<form onSubmit={btnHandler}>
<input type="text" onChange={(e) => (typedNumber = e.target.value)} />
<input type="submit" />
</form>
<p>{number}</p>
</div>
);
}
export default App;

Categories

Resources