how to check if string contains number with react - reactjs

I am building a user validation website, I want each input to verify if the string that was entered:
Have uppercase first letter
doesn't contain numbers
doesn't contain "$%^&*()"
I did the first task, but I can't do the last ones.
I have tried !isNaN(firstName) === true and it wont work
import React, { Component } from 'react';
class Profile extends Component {
state = {
details: {
firstName: '',
lastName: '',
ID: '',
Email: ''
},
error: false,
complete: false
};
OnSubmit = e => {
e.preventDefault();
const { firstName } = this.state.details;
if (
firstName.charAt(0) !== firstName.charAt(0).toUpperCase() &&
!isNaN(firstName) === true
) {
this.setState({ error: true });
} else {
this.setState({ complete: true });
}
};
OnChange = e => {
e.preventDefault();
this.setState({
details: { ...this.state.details, [e.target.name]: e.target.value }
});
};
render() {
return (
<div>
<div className="container text-center mt-4" style={{ width: '500px' }}>
<form className="px-4 py-3" onSubmit={this.OnSubmit}>
<div className="form-group">
{this.state.error === true ? (
<p className="text-danger">
Some of the details are wrong check the fields above
</p>
) : null}
<label>First Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="firstName"
/>
</div>
<div className="form-group">
<label>Last Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="lastName"
/>
</div>
<div className="form-group">
<label>ID Number:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="ID"
/>
</div>
<div className="form-group">
<label>Email:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="Email"
/>
</div>
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
</form>
</div>
</div>
);
}
}
export default Profile;

function validateName(name) {
var isValidName = true;
if(/[!##$%^&*(),.?":{}|<>]/g.test(name) || !/^[A-Z]/.test(name) || /\d+/g.test(name)) {
isValidName = false;
}
return isValidName;
}
validateName("David")

You can use regex.
!firstName.match(/\d/)
\d checks for the numbers

First split firstName, then check for Number in that array
OnSubmit = e => {
e.preventDefault();
const { firstName } = this.state.details;
let firstNameArr = firstName.split('');
for(value of firstName.split('')){
if (!isNaN(value) {
this.setState({ error: true });
} else {
this.setState({ complete: true });
}
}
};

This is how I would do it:
const test1 = "%2mfas1k";
const test2 = '123';
const test3 = 'test';
function test(str) {
const match = str.match(/\d+/g);
const isArray = Array.isArray(match);
if(isArray) return match.map(Number);
return false
}
// If test return a result not falsy, contains a number
console.log(test(test1)); // [2, 1]
console.log(test(test2)); // [123]
console.log(test(test3)); // false

Here is a working example, i have split each part into its own checker to make it easier to understand.
let string = "Asdfsdf$32";
let special_characters = ['$','%','^','&','*','(',')'];
let string_array = string.split('');
// Upper case check
if(string[0] === string[0].toUpperCase()) {
console.log("First letter is uppercase")
} else {
console.log("First letter is not uppercase")
}
// No numbers check
if(string.match(/\d/)) {
console.log("Digit Found")
} else {
console.log("No Digit Found")
}
// Special Characters
if(string_array.find(item => special_characters.includes(item))) {
console.log("Special Character Found")
} else {
console.log("No Special Character Found")
}

export function checkDigit(username){
if(username.match(/\d/)) {
console.log("Digit Found")
return true;
}else {
return false;
}
}
let username = this.state.name;
if(checkDigit(username)){
showInfoAlert(NAME_VALIDATION_DIGIT)
return
}

Related

In my react js validateProperty Function returns a undefined property

I am using a Latest Version of Linux
login.jsx
import React, { Component } from "react";
import Input from "./common/input";
class Login extends Component {
state = {
account: {
username: "",
password: "",
},
errors: {},
};
validate = (input) => {
const errors = {};
const { account } = this.state;
if (account.username.trim() === "") {
errors.username = "Username is Required";
}
if (account.password.trim() === "") {
errors.password = "Password is Required";
}
return Object.keys.length === 0 ? null : errors;
};
handleSubmit = (e) => {
e.preventDefault();
const errors = this.validate();
// console.log(errors);
this.setState({ errors: errors || {} });
if (errors) return;
// Call the Server
console.log("Submitted");
};
validateProperty = ({ name, value }) => {
if (name === "username") {
if (value.trim === "") return "Username is Required";
}
if (name === "password") {
if (value.trim === "") return "Password is Required";
}
};
handleChange = ({ currentTarget: input }) => {
const errors = { ...this.state.errors };
const errorMessage = this.validateProperty(input);
console.log(errorMessage);
if (errorMessage) errors[input.name] = errorMessage;
else delete errors[input.name];
const account = { ...this.state.account };
account[input.name] = input.value;
this.setState({ account, errors });
};
render() {
const { account, errors } = this.state;
return (
<div className="container ">
<div className="row justify-content-center">
<div className="col-md-6">
<div className="card mt-5">
<div className="card-header">
<h1 className="text-center">Login</h1>
</div>
<div className="card-body">
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={account.username}
onChange={this.handleChange}
label="Username"
type="text"
error={errors.username}
/>
<Input
name="password"
value={account.password}
onChange={this.handleChange}
label="Password"
type="password"
error={errors.password}
/>
<div className="text-center">
<button className="btn btn-primary">Log in</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Login;
On top i have a function called validateProperty this function returns undefined I need your help Guys
I print the function in also console it return a undefined what can i do ?
Thanks in Advance <3
I print the function in also console it return a undefined what can i do ?
Thanks in Advance <3
When the function will return undefined?
You probably wanted this:
return Object.keys(errors).length === 0 ? null : errors
Because
Object.keys.length
is always equal 1

Better way to check input values of a form in React/Next Js

I've written a simple form for my web application. I plan on writing a feature that checks to make sure all fields are non-empty and valid, and displaying an error message as a component if not. This is the skeleton:
import { useState } from 'react';
import emailjs from "emailjs-com";
import apiKeys from "../public/credentials/apikeys";
import ContactStyles from "../public/styles/ContactStyles";
function ContactForm() {
const [fieldDict, setFieldDict] = useState(
{
name: "",
email: "",
subject: "",
message: ""
});
function sendEmail(e) {
e.preventDefault();
// TODO: Show success or error message
var blankField = false;
if (fieldDict.name.length === 0) {
console.log("No name"); // To be implemented here and on subsequent lines
blankField = true;
}
if (fieldDict.email.length === 0) {
console.log("No email");
blankField = true;
}
if (fieldDict.subject.length === 0) {
console.log("No subject");
blankField = true;
}
if (fieldDict.message.length === 0) {
console.log("No message");
blankField = true;
}
if (blankField) { return }
emailjs.sendForm(apiKeys.serviceID, apiKeys.templateID, e.target, apiKeys.userID)
.then((result) => {
console.log(result, fieldDict);
}, (error) => {
console.log(error, fieldDict);
});
e.target.reset();
}
return (
<div className="contact-section">
<div className="contact-container">
<h5 className="form-header">Send me an email!</h5>
<form className="contact-form" onSubmit={sendEmail}>
<div className="form-group">
<label className="label">Name</label>
<input className="input" type="text" name="name" autoComplete="off"
onInput={e => {
setFieldDict(prevFieldDict => ({...prevFieldDict, name: e.target.value}));
}}/>
</div>
<div className="form-group">
<label className="label">Email</label>
<input className="input" type="email" name="email" autoComplete="off"
onInput={e => {
setFieldDict(prevFieldDict => ({...prevFieldDict, email: e.target.value}));
}}/>
</div>
<div className="form-group">
<label className="label">Subject</label>
<input className="input" type="subject" name="subject" autoComplete="off"
onInput={e => {
//? Viability of this method?
setFieldDict(prevFieldDict => ({...prevFieldDict, subject: e.target.value}));
}}/>
</div>
<div className="form-group">
<label className="label">Message</label>
<textarea className="input textarea" name="message" rows="6"
onInput={e => {
setFieldDict(prevFieldDict => ({...prevFieldDict, message: e.target.value}));
}}/>
</div>
<div className="submit">
<button type="submit" value="Send">Submit</button>
</div>
</form>
</div>
<style jsx global>{ContactStyles}</style>
</div>
);
}
export default ContactForm;
With every keystroke, the corresponding key (name, email, subject, message) gets updated.
Question
Is there a better way to do this? A more efficient way to do this seems to be only updating the fieldDict dictionary when the use hits submit, but based on how react renders components does this really matter?
Note: The code as is works just fine, I'm just asking if there is a better way to do this? If you want a better way of seeing this, change the content of onInput{...} to e => console.log(e.target.value).
Any insight is much appreciated!
You can iterate through your dict and filter all names that are falsable.
function sendEmail(e) {
e.preventDefault();
const blankFields = Object.keys(fieldDict).filter(fieldName => !fieldDict[fieldName])
blankFields.forEach(fieldName => console.log(`no ${fieldName}`);
if (blankFields.length) { return }
emailjs.sendForm(apiKeys.serviceID, apiKeys.templateID, e.target, apiKeys.userID)
.then((result) => {
console.log(result, fieldDict);
}, (error) => {
console.log(error, fieldDict);
});
e.target.reset();
}

Submit works with second try

I am validating some details, the problem is when the validation is complete and I want to move to the next page with submit, the first time it's receiving the data, and the second time it's checking if the data is true and moves me to the next page.
I have tried to put all the validation process to the OnChange function, but it messes up all of the validation process, I have also tried to put the error variables to the state but I receive an error message that It's constant variables and can't be changed.
import { Link } from 'react-router-dom';
class Profile extends Component {
state = {
details: {
firstName: '',
lastName: '',
id: '',
email: ''
},
error: false,
complete: false
};
OnSubmit = e => {
e.preventDefault();
let re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const { email } = this.state.details;
const { firstName } = this.state.details;
const { lastName } = this.state.details;
const { id } = this.state.details;
let errorid = false;
let errorfirstlast = false;
let erroremail = false;
if (id.length <= 9 && id !== '') {
console.log('trueid');
errorid = false;
} else {
errorid = true;
console.log('falseid');
}
if (re.test(email)) {
console.log('trueemail');
erroremail = false;
} else {
erroremail = true;
console.log('falseemail');
}
if (
firstName !== '' &&
lastName !== '' &&
firstName.substr(0, 1) === firstName.substr(0, 1).toUpperCase() &&
lastName.substr(0, 1) === lastName.substr(0, 1).toUpperCase() &&
!firstName.match(/\d/) &&
!lastName.match(/\d/)
) {
console.log('truefirstlast');
errorfirstlast = false;
} else {
errorfirstlast = true;
console.log('falsefirstlast');
}
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState({ error: true });
} else {
this.setState({ error: false });
this.setState({ complete: true });
}
};
OnChange = e => {
e.preventDefault();
this.setState({
details: { ...this.state.details, [e.target.name]: e.target.value }
});
};
render() {
return (
<div>
<div className="container text-center mt-4" style={{ width: '500px' }}>
<form className="px-4 py-3" onSubmit={this.OnSubmit}>
<div className="form-group">
{this.state.error === true ? (
<p className="text-danger">
Some of the details are wrong check the fields above
</p>
) : null}
<label>First Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="firstName"
/>
</div>
<div className="form-group">
<label>Last Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="lastName"
/>
</div>
<div className="form-group">
<label>ID Number:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="id"
/>
</div>
<div className="form-group">
<label>Email:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="email"
/>
</div>
{this.state.complete === true ? (
<Link to="/success">
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
</Link>
) : (
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
)}
</form>
</div>
</div>
);
}
}
export default Profile;
The problem is that I enter the next page with the second click on the submit button, I want to enter with the first try
The reason is that this.setState(..) is an async function Reference here.
Moreover you're calling multiple state-operations behind each other instead of putting it in one call like:
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState({ error: true });
} else {
this.setState({
error: false,
complete: true
});
}
If you want to to an action after this state operation is done you can add a callback to the operation:
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState({ error: true });
} else {
this.setState({
error: false,
complete: true
}, this.submitMyStuff);
}
const submitMyStuff = () => {
// submit all my stuff
}

cannot update field on Change

i have 3 update textfields, the value of which is coming from a state called edit_obj, like so:
<input type="text" noValidate name="uname_edit" value={this.state.edit_obj.username} onChange={e => this.editchangeHandler(e)} />
when i click on 'edit' button, editClick function works that sets the value of edit_obj like so:
this.setState({edit_obj: editval})
I am attaching the full code. Please let me know how i can edit the value d the textfield:
import React from 'react';
import {FromErrors1} from './formErrors';
import { SlowBuffer } from 'buffer';
class Form extends React.Component{
constructor(props){
super(props);
this.state={
uname: '',
pass: '',
address:'',
salary:'',
addFormValues:{
username:'',
password:'',
address:''
},
errorfields:{
uname_err:'',
pass_err:'',
address_err:'',
salary_err:'',
valid_user:false,
valid_pass:false,
valid_address:false,
valid_salary:false,
},
delete_data:[],
edit_showui:false,
edit_obj:{},
editval:{},
edit_data:[],
editted_uname:''
}
this.changeHandler= this.changeHandler.bind(this)
this.pushAddStudentData=new Array()
this.submitForm= this.submitForm.bind(this);
//this.editchangeHandler = this.editchangeHandler.bind(this)
//this.editClick = this.editClick.bind(this)
}
editClick =(that,editval) =>{
//alert("du")
//show edit ui:
this.setState({edit_showui:true});
//add values to the inputs of show ui
console.log('editval: ',editval);
//this.setState({edit_obj:editval});
//this.setState({edit_data:this.state.edit_data.push(editval)});
/*this.setState((state)=>({
edit_data:state.edit_data.push(editval)
}))*/
this.state.edit_data=[]
this.setState(prevState => ({
edit_data: [...prevState.edit_data, editval]
}))
this.setState({edit_obj: editval})
console.log("edit_obj:::::::",this.state.edit_obj)
}
editchangeHandler = (e) =>{
console.log('ename::',e.target.name)
console.log('etarget::',e.target.value)
//this.setState({[e.target.name]:e.target.value})
console.log('edit_obj::',this.state.edit_obj)
//newEditVal
//this.state.newEditVal.username =
/*
if(e.target.name=='uname_edit'){
console.log('uname_edit')
//editted_uname
this.setState(
{editted_uname : ''}
)
console.log('editted_uname::',this.state.editted_uname)
}
if(e.target.name=='pass_edit'){
console.log('pass_edit')
}
if(e.target.name=='address_edit'){
console.log('address_edit')
}
*/
//this.setState({})
this.setState({
[e.target.name]: e.target.value
});
}
updateval=()=>{
console.log('EDIT_OBJ: ',this.state.edit_obj)
}
deleteClick =(e,f) =>{
console.log("sefr",e,'a::',f);
// if(this.pushAddStudentData.indexOf(f) > -1){
// }
let finaldeleteddata=[];
for( var i = 0; i < this.state.delete_data.length; i++){
console.log('this.state.delete_data[i]===f:: ',this.state.delete_data[i]===f)
console.log('and f:: ',f)
if ( this.state.delete_data[i] === f) {
this.state.delete_data.splice(i, 1);
// this.setState(
// {
// delete_data:finaldeleteddata
// }
// )
this.setState(prevState => ({
delete_data: [...prevState.delete_data]
}))
}
console.log('YEYEYEYEEDITDATATAa:: ',this.state.delete_data)
console.log("finaldeleteddata:: ",finaldeleteddata)
}
}
changeHandler = (ev) =>{
// alert("gugugu")
this.setState({[ev.target.name]:ev.target.value})
console.log(this.state)
}
submitForm = (e) =>{
let finaladdeddata;
e.preventDefault();
console.log('this.state.uname:',this.state.uname);
console.log('this.state.pass:',this.state.pass);
let usererror = {...this.state.errorfields};
var regex_username = new RegExp(/^[a-zA-Z ]*$/);
if(this.state.uname && regex_username.test(this.state.uname)){
//no error
// this.state.valid_user= true; /THIS IS NOT RIGHT WAY, USE THIS.SETSTATE
alert("iffff");
usererror.uname_err='';
usererror.valid_user = true
console.log("usererror::",usererror)
console.log("this.STATEuserif:::",this.state.errorfields.valid_user)
this.setState({errorfields: usererror});
}else{
//else of user
alert('2user')
console.log('usererror: ',usererror)
usererror.uname_err= 'username not valid';
usererror.valid_user = false;
this.setState({errorfields: usererror});
//there is error
console.log("this.STATEuserelse:::",this.state)
}
if(this.state.pass && this.state.pass.length <=6){
//if of pass
//no error
// this.state.valid_pass= true;
usererror.valid_pass=true;
usererror.pass_err='';
this.setState({errorfields:usererror})
console.log("this.STATEpassif:::",this.state)
}else{
//else of pass
alert('2pass')
usererror.valid_pass=false;
usererror.pass_err='invalid password | password length more than 6';
this.setState({errorfields:usererror})
//there is error
console.log('this.state.errorfields',this.state.errorfields)
console.log("this.STATE2:::",this.state)
}
//usererror
//errorfields
console.log("address:", this.state.address)
console.log("salary:", this.state.salary)
//put error fields in address
if(this.state.address && this.state.address.length<=20){
// this.state.valid_address=true;
usererror.address_err='';
usererror.valid_address=true
this.setState({errorfields:usererror})
} else{
usererror.address_err='Empty address | address length more than 20';
usererror.valid_address=false
this.setState({errorfields:usererror})
}
/*form={}
uname: '',
pass: '',
address:''
}*/
console.log('usererror.valid_address',usererror.valid_address);
console.log('usererror.valid_pass',usererror.valid_pass);
console.log('usererror.valid_user',usererror.valid_user);
if(usererror.valid_address==true && usererror.valid_pass==true && usererror.valid_user==true){
alert("YESSS");
let addFormValues_dupl= {...this.state.addFormValues};
addFormValues_dupl.username = this.state.uname;
addFormValues_dupl.password = this.state.pass;
addFormValues_dupl.address = this.state.address;
console.log('addFormValues_dupl',addFormValues_dupl);
// this.pushAddStudentData.push(addFormValues_dupl)
//this.setState({delete_data:addFormValues_dupl})
this.state.delete_data.push(addFormValues_dupl)
console.log('state',this.state);
// this.setState({addFormValues: this.state.uname})
}else{
alert("NOOO")
//this.pushAddStudentData=[]
console.log('pushAddStudentDataELSE',this.pushAddStudentData[0]);
}
}
render(){
return(
<div>
<h2>Add Employee info</h2>
<div className="displayerrors">
{/* <ul>{this.state.errorfields.map((a,i)=>{<li>a</li>})}</ul> */}
<input type="hidden" value={this.state.errorfields}/>
<p>{this.state.errorfields.uname_err} - {this.state.errorfields.valid_user}</p>
<p>{this.state.errorfields.pass_err}</p>
<p>{this.state.errorfields.address_err}- {this.state.errorfields.valid_address}</p>
</div>
<div>
<label>username:</label>
<input type="text" noValidate name="uname" onChange={this.changeHandler}/>
</div>
<div>
<label>password:</label>
<input type="password" noValidate name="pass" onChange={this.changeHandler}/>
</div>
<div>
<label>address:</label>
<textarea noValidate name="address" onChange={this.changeHandler}></textarea>
</div>
<div>
<button onClick={this.submitForm}></button>
</div>
<div>{this.state.delete_data.length}
{this.state.delete_data.map((a,i)=>{
return <ul key={i}> <li>{i}</li><li>{a.username}</li>
<li>{a.password}</li>
<li>{a.address}</li>
<li><a href="#" onClick={()=>{this.deleteClick(this,a)}}>Delete</a></li>
<li><a href="#" onClick={()=>{this.editClick(this,a)}}>Edit</a></li></ul>
})}
</div>
{ this.state.edit_showui==true &&
<div>
<div>
<label>username:</label>
<input type="text" noValidate name="uname_edit" value={this.state.edit_obj.username} onChange={e => this.editchangeHandler(e)} />
</div>
<div>
<label>password:</label>
<input type="password" noValidate name="pass_edit" value={this.state.edit_obj.password} onChange={this.editchangeHandler.bind(this)} />
</div>
<div>
<label>address:</label>
<textarea noValidate name="address_edit" value={this.state.edit_obj.address} onChange={this.editchangeHandler.bind(this)}></textarea>
</div>
<div>
<button onClick={this.updateval.bind(this)}>update</button>
</div>
<div>{this.state.edit_obj.username}</div>
<div>{this.state.edit_obj.password}</div>
<div>{this.state.edit_obj.address}</div>
</div>
}
editdata:
<div>{this.state.edit_data.username}</div>
<div>{this.state.edit_data.password}</div>
<div>{this.state.edit_data.address}</div>
{this.state.edit_data.map((q,i)=>{
return <ul key={i}> <li>{i}</li><li>{q.username}</li>
<li>{q.password}</li>
<li>{q.address}</li>
</ul>
})}
}
</div>
)//return ends
}
}
export default Form;
thanks in advance.

How do I set the state of a parent from a child in react?

I am making a form wizard in React Js. In the first step, I want to hide/display a form base on radio input value. I want to set the state of the parent based on the input from a visible form. Basically, I want to check if a user exists or not and then take the appropriate action. If they exist, I enter their username, if not I enter the registration details. Here is my code
class Step1 extends React.Component {
constructor(props) {
super(props);
this.state = {
userExists: 'false',
username: '',
register: {
full_name: '',
phone_number: '',
id_number: '',
gender: ''
},
submitted: false,
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleUserExistsCheck = this.handleUserExistsCheck.bind(this);
}
handleChange(event) {
const { name, value } = event.target;
this.setState({
[name]: value
});
}
handleUsernameChange(event) {
const { name, value } = event.target;
const { username} = this.state;
this.setState({
username: username
});
}
handleRegisterChange(event) {
const { register } = this.state;
const { name, value } = event.target;
this.setState({
register: {
...register,
[name]: value
}
});
}
handleUserExistsCheck(event) {
this.setState({
...this.state,
userExists: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
this.setState({
...this.state,
submitted: true
});
// TODO: Dispatch based on checkbox
}
_validate() {
let { user } = this.state
this.props.afterValid({
// TODO submit data to wizard
});
}
handleReset() {
this.setState({
...this.state,
userExists: false,
username: '',
full_name: '',
phone_number: '',
id_number: '',
gender: '',
submitted: false,
});
}
render() {
if (this.props.currentStep !== 1) {
return null;
}
const { userExists, username, register } = this.state;
console.log(register)
return(
<div>
<CardHeader>Does the user have an account?</CardHeader>
<CardBody>
<form onSubmit={this.handleSubmit}>
<div>
<input type="radio" value="true" checked={ userExists ==="true"}
onChange={this.handleUserExistsCheck} name="userExists"/> Yes
{' '}
<input type="radio" value="false" checked={ userExists ==="false"}
onChange={this.handleUserExistsCheck} name="userExists"/> No
</div>
{' '}
<PersonalDetails register={register}
username={username}
handleRegisterChange={this.handleRegisterChange}
handleUsernameChange={this.handleUsernameChange}
userExists={userExists}/>
{' '}
<div className="clearfix">
<button type="submit" className="btn btn-primary mb-2 float-right">Next</button>
</div>
</form>
</CardBody>
</div>
);
}
}
function UsernameForm(props) {
return (
<FormGroup>
<label>Username</label>
<Input type="text" name="username" value={props.username}
onChange={props.onChange} placeholder="Username"/>
</FormGroup>
)
}
function RegisterForm(props) {
return(
<div>
<FormGroup>
<label>Full Name</label>
<Input type="text" name="full_name" value={props.register.full_name}
onChange={props.onChange} placeholder="Full Name"/>
</FormGroup>
<FormGroup>
<label>Phone Number</label>
<Input type="text" name="phone_number" value={props.register.phone_number}
onChange={props.onChange} placeholder="Phone Number"/>
</FormGroup>
<FormGroup>
<label>ID Number</label>
<Input type="text" name="id_number" value={props.register.id_number}
onChange={props.onChange} placeholder="ID Number"/>
</FormGroup>
<FormGroup>
<label htmlFor="gender">Gender</label>
<select value={props.register.gender} onChange={props.onChange}
className="custom-select custom-select-lg mb-3" name="gender">
<option value="">----</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</FormGroup>
</div>
);
}
function str2bool(value) {
if (typeof(value) === 'string') {
if (value.toLowerCase() === 'true') return true;
if (value.toLowerCase() === 'false') return false;
}
return value;
}
function PersonalDetails(props) {
let { userExists } = props;
userExists = str2bool(userExists);
if (userExists == true) {
return <UsernameForm username={props.username} onChange={props.handleUsernameChange}/>
} else {
return <RegisterForm register={props.register} onChange={props.handleRegisterChange}/>
}
}
const connectedStep1 = connect(null, null)(Step1);
export { connectedStep1 as Step1 };
Currently, I am getting the error Uncaught TypeError: Cannot read property 'state' of undefined
Create a method in the parent component to update the state, then pass this method to the child component as a prop. When you call this prop in the child it will update the parent state.

Resources