Validating form inputs with React - javascript

I am trying to check that the required fields are not empty and making sure that the input type is correct.
const CreateSensor = () => {
const [deveui, setDeveui] = useState('');
const [location, setLocation] = useState('');
const [levelid, setLevel] = useState('');
const submitValue = () => {
let data = {deveui,location,levelid};
//POST method
fetch("api")
ClearFields();
}
function ClearFields(){
document.getElementById("dev").value = "";
document.getElementById("location").value = "";
document.getElementById("level").value = "";
}
return(
<>
<hr/>
<input type="text" id="dev" placeholder="deveui" onChange={e => setDeveui(e.target.value)} />
<input type="text" id="location"placeholder="Location" onChange={e => setLocation(e.target.value)} />
<input type="text" id="level" placeholder="Levelid" onChange={e => setLevel(e.target.value)} />
<button onClick={submitValue}>Submit</button>
</>
)
}
the submit button will check whether deveui is not empty and the levelid is set to an integer.
I have tried changing the input type for levelid to numbers but there is arrows on it which I feel is unnecessary.

I strongly recommend using a React form library. Here's an example with react-hook-form
import { useForm } from "react-hook-form";
const CreateSensor = () => {
const {
register,
handleSubmit,
watch,
reset,
formState: { errors },
} = useForm({ defaultValues: { deveui: "", location: "", levelid: "" } });
const submitValue = ({deveui, location, levelid}) => {
// exclude 'deveui' from fetch payload
const payload = { location, levelid }
// POST data to api, for example
fetch("https://myapi.com", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
// reset form state
}).then((response) => reset());
};
return (
<>
<hr />
<form onSubmit={handleSubmit(submitValue)}>
<input
{...register("deveui", { required: true })}
type="text"
id="dev"
placeholder="deveui"
/>
<input
{...register("location", { required: true })}
type="text"
id="location"
placeholder="Location"
/>
<input
{...register("levelid", { required: true })}
type="text"
id="level"
placeholder="Levelid"
/>
<button type="submit">Submit</button>
</form>
</>
);
}

Related

Why am I getting an error when creating a new news entry page?

I am working with GraphQL and React and I have next post form code:
const PostForm = props => {
// set the default state of the form
const [values, setValues] = useState();
// update the state when a user types in the form
const onChange = event => {
setValues({
...values,
[event.target.name]: event.target.value
});
};
return (
<Wrapper>
<Form
onSubmit={event => {
event.preventDefault();
props.action({
variables: {
...values
}
});
}}
>
<label htmlFor="title">Title Post:</label>
<input
required
type="text"
id="title"
name="title"
placeholder="title"
onChange={onChange}
/>
<label htmlFor="category">Category Post:</label>
<input
required
type="text"
id="category"
name="category"
placeholder="category"
onChange={onChange}
/>
<TextArea
required
type="text"
name="body"
placeholder="Post content"
onChange={onChange}
/>
<Button type="submit">Save</Button>
</Form>
</Wrapper>
);
};
This code I have in the new post page:
const NEW_POST = gql`
mutation createPost($title: String, $category: String, $body: String) {
createPost(title: $title, category: $category, body: $body) {
_id
title
createdAt
updatedAt
body
author {
name
}
comments{
text
}
}
}`;
const NewPost = props => {
useEffect(() => {
document.title = 'NewPost - Notedly';
});
const [ data, { loading, error } ] = useMutation(NEW_POST, {
onCompleted: data => {
props.history.push(`posts/${data.createPost._id}`);
}
});
return (
<React.Fragment>
{loading && <p> loading...</p>}
{error && <p>Error saving the note</p>}
{console.log(data)}
<PostForm action={data} />
</React.Fragment>
);
};
I have the following mutation code, for example:
mutation{
createPost(title: "my jobs", category: "6251ef28413373118838bbdd", body: "smdbsdfsjns"){
_id
title
category
{catname}
body
}
}
I don't understand why I am getting this error:
"Uncaught (in promise) Error: Network error: Response not successful: Received status code 400"

onSubmit React js problems

I have a problem with React JS.
I have a form where the user has to pick some options and then write a number, when the user press a button named "Consultar" or press "Enter" (Intro) it suposed to send the form and show a table with the necessary information.
However, when the user press "Enter" the form information is not submitted, the only way is by pressing the button named "Consultar". I have tried using onKeyPress but it did not work.
Could it be some react bug causing the problem and not my code? If it is not something in my code, what I need is that the user can press "Enter" and that it does the same function of the "Consultar" button.
Please help, I am very new in this world of React JS. Here is the code:
const DataForm = ({
update,
setIsLoaded,
setError,
}) => {
const formatChars = { C: '[1-9]', L: '[0-9]', Z: '[0-9]?' };
const [tipoCedula, setTipoCedula] = useState('1');
const [tipoBusqueda, setTipoBusqueda] = useState('1');
const [numCedula, setNumCedula] = useState('');
const [emailAddress, setEmailAddress] = useState('');
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
tipoCedula,
tipoBusqueda,
numCedula,
emailAddress,
});
const getNumCedulaMask = (pTipoCedula) => {
if (pTipoCedula === '2') return 'C-LLL-LLLLLL';
if (pTipoCedula === '3') return 'CLLLLLLLLLLZ';
if (pTipoCedula === '4') return 'CLLLLLLLLL';
return 'C-LLLL-LLLL';
};
const getRegExFromMask = (pMask, pFormatChars) => {
let returnValue = pMask;
Object.keys(pFormatChars).map((item) => {
if (typeof returnValue.replaceAll === 'function') {
returnValue = returnValue.replaceAll(item, pFormatChars[item]);
}
return returnValue;
});
return new RegExp(`^${returnValue}$`);
};
const numCedulaMask = getNumCedulaMask(tipoCedula);
const numCedulaRegEx = getRegExFromMask(numCedulaMask, formatChars);
const emailRegEx = '^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$';
const isValidNumCedula = (inputValue) => {
const replace = inputValue.replace('_', '');
if (replace.match(numCedulaRegEx)) {
return true;
}
return 'El formato no es válido';
};
const isValidEmail = (inputValue) => {
if (inputValue.match(emailRegEx)) {
return true;
}
return 'El formato no es válido';
};
const onSubmit = async (data) => {
let searchParameter = '';
if (data.tipoBusqueda === '1') {
searchParameter = data.numCedula;
} else {
searchParameter = data.emailAddress;
}
const { ssoBaseUrl } = some restricted information
const apiCall = some restricted information
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
};
setIsLoaded(true);
try {
const result = await fetch(apiCall, requestOptions);
const datos = await result.json();
setIsLoaded(false);
update('reminderResult', datos);
} catch (e) {
setError(true);
}
};
return (
<div>
<form onSubmit={handleSubmit(onSubmit)} id='formulario' data-testid='formulario-busqueda'>
<div className='form-group group_TIPO_BUSQUEDA'>
<label className='label'>Buscar por</label>
<div>
<select data-testid="search-type"
className='form-control select TIPO_BUSQUEDA'
{...register('tipoBusqueda')}
defaultValue={tipoBusqueda}
onChange={(e) => (setTipoBusqueda(e.target.value))}
>
<option value='1'>Tipo de cedula</option>
<option value='2'>Email</option>
</select></div>
</div>
{tipoBusqueda === '1' && <div className='form-group group_TIPO_CEDULA'>
<label htmlFor='tipoCedula' className='label'>Tipo de cédula</label>
<div>
<select data-testid="cedula-tipo-id"
className='form-control select TIPO_CEDULA'
{...register('tipoCedula')}
defaultValue={tipoCedula}
onChange={(e) => (setTipoCedula(e.target.value))}
>
<option value='1'>Cédula Persona Física</option>
<option value='2'>Cédula Persona Jurídica</option>
<option value='4'>Número Identificación Tributario Especial (NITE)</option>
<option value='3'>Documento Identificación Migratorio Extranjeros</option>
</select>
{errors.tipoCedula && <p className='error-message'>{errors.tipoCedula.message}</p>}
</div>
</div>
}
{tipoBusqueda === '1' && <div className='form-group group_NUM_CEDULA'>
<label htmlFor='numCedula' className='label'>Cédula</label>
<div>
<InputMask data-testid="num-cedula"
className='form-control NUM_CEDULA input'
{...register('numCedula', {
required: {
value: true,
message: 'Este campo es requerido',
},
validate: {
validValue: isValidNumCedula,
},
})}
formatChars={formatChars}
onChange={(e) => (setNumCedula(e.target.value))}
value={numCedula}
mask={numCedulaMask}
/>
{errors.numCedula && <p className='error-message' role="alert">Formato cédula incorrecto</p>}
</div>
</div>}
{tipoBusqueda === '2' && <div className='form-group'>
<label htmlFor='emailAddress' className='label'>Dirección de correo electrónico</label>
<div>
<input type="text"
data-testid="emailAddress"
className="form-control"
value={emailAddress}
{...register('emailAddress', {
required: 'Este campo es requerido',
validate: {
validValue: isValidEmail,
},
})}
onChange={(e) => (setEmailAddress(e.target.value))}
/>
{errors.emailAddress && <p className='error-message' role="alert">{errors.emailAddress.message}</p>}
</div>
</div>}
<div className='form-group'>
<button className='btn-submit float-right' type="submit" data-testid="button-ask">CONSULTAR</button>
</div>
</form>
</div>
);
};
DataForm.propTypes = {
update: PropTypes.func.isRequired,
setIsLoaded: PropTypes.func.isRequired,
setError: PropTypes.func.isRequired,
};
export default DataForm;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I did not try your code, but i saw your code and i find here something. You have to write to arrow function in onSubmit.
<form onSubmit={() => handleSubmit(onSubmit)} id='formulario' data-testid='formulario-busqueda'>
If your page getting refresh on submit, then you have to write event.preventDefault() onSubmit.
<form onSubmit={(event) => {
event.preventDefault();
handleSubmit(onSubmit);
} id='formulario' data-testid='formulario-busqueda'>
Here is a code example how to submit forms with enter key:
import React, { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log('form submited');
};
return (
<div>
<form onSubmit={handleSubmit} >
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</form>
</div>
);
}
....
You don't have a handleSubmit function, what you have is an onSubmit function. Therefore, in your onSubmit event listener, you are trying to call a non-existent function
<form onSubmit={handleSubmit(onSubmit)}...
This is how you should call the onSubmit function
<form onSubmit={onSubmit}...

Password States are reacting one character late

Im checking to see if the register forms passwords match, and when they do, something changes. but its happening on 1 "onChange" too late. Ex. User enters "DOG" as the password. when the retype it in the 2nd input, "DOG" doesnt work. but it does if they enter another character or delete one character (Ex. "DOGX" or deleting "G" so its "DO")
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import "./register.css";
function RegisterBoard() {
const history = useHistory();
const [register, changeRegister] = useState({
password: false,
repeatPassword: false,
});
const [info, changeInfo] = useState({
password: "",
repeatPassword: "",
});
const changeValue = (e) => {
const { name, value } = e.target;
changeInfo((prev) => {
return {
...prev,
[name]: value,
};
});
};
const input = (e) => {
const target = e.target.dataset.name;
if (target != "repeatPassword") {
changeRegister({
...register,
[target]: true,
});
} else {
if (info.password != info.repeatPassword) {
changeRegister({
...register,
repeatPassword: false,
});
} else {
changeRegister({
...register,
repeatPassword: true,
});
}
}
};
return (
<div className="registration-form">
<form>
<div>
<input
name="password"
data-name="password"
onChange={(e) => {
changeValue(e);
input(e);
}}
className="password"
type="password"
placeholder="ENTER YOUR PASSWORD HERE"
/>
<div className="animated-button">
</div>
</div>
<div>
<input
id="pwd"
name="repeatPassword"
data-name="repeatPassword"
onChange={(e) => {
changeValue(e);
input(e);
}}
className="repeat-password"
type="password"
placeholder="REPEAT YOUR PASSWORD HERE"
/>
</div>
</div>
</form>
</div>
);
}
export default RegisterBoard;
I guess this is because you are calling both 'changeValue' and 'input' functions within the inputs onChange attribute. Since they are firing at the same time, 'input' is not using the most recent value for 'info', because 'changeValue' hasn't set the new state yet.
Either call the input function within a useEffect hook which is dependent on changes to 'info's' state, or use e.target.value instead of info's state within the 'input' function to compare info.password != info.repeatPassword
EDIT: here is the useEffect way, it simplifies it and you can remove your input function completely: https://codesandbox.io/s/jolly-khorana-8s63b?file=/src/App.js
import React, { useState, useEffect } from "react";
import "./styles.css";
function RegisterBoard() {
const [register, changeRegister] = useState({
password: false,
repeatPassword: false
});
const [info, changeInfo] = useState({
password: "",
repeatPassword: ""
});
const changeValue = (e) => {
const { name, value } = e.target;
changeInfo((prev) => {
return {
...prev,
[name]: value
};
});
};
useEffect(() => {
let password = false;
let repeatPassword = false;
if (info.password !== "") {
password = true;
if (info.password === info.repeatPassword) {
repeatPassword = true;
}
}
changeRegister({ password, repeatPassword });
}, [info]);
return (
<div className="registration-form">
<form>
<div>
<input
name="password"
data-name="password"
onChange={changeValue}
className="password"
type="password"
placeholder="ENTER YOUR PASSWORD HERE"
/>
<div className="animated-button"></div>
</div>
<div>
<input
id="pwd"
name="repeatPassword"
data-name="repeatPassword"
onChange={changeValue}
className="repeat-password"
type="password"
placeholder="REPEAT YOUR PASSWORD HERE"
/>
</div>
</form>
<div>{info.password}</div>
<div>{info.repeatPassword}</div>
<div>{register.repeatPassword ? "match" : "don't match"}</div>
</div>
);
}
export default function App() {
return (
<div className="App">
<RegisterBoard />
</div>
);
}
You're definitely going to want to implement a useEffect here to update the UI every time the password & repeatPassword state changes, to ensure that after the last character is typed that you get the full password. Inside the useEffect is where you'll write your conditional logic. What I provided is just a good example...
import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import "./register.css";
function RegisterBoard() {
const history = useHistory();
const [password, setPassword] = useState('')
const [repeatPassword, setRepeatPassword] = useState('')
//const [register, changeRegister] = useState(false);
const changeValue = (e) => {
const { name, value } = e.target.value;
const input = (e) => {
const target = e.target.dataset.name;
if (target != "repeatPassword") {
changeRegister({
...register,
[target]: true,
});
} else {
if (info.password != info.repeatPassword) {
changeRegister({
...register,
repeatPassword: false,
});
} else {
changeRegister({
...register,
repeatPassword: true,
});
}
}
};
useEffect(() => {
if((password !== "" && repeatPassword !== "") && (password !==
repeatPassword)){
console.log("PASSWORDS DO NOT MATCH!!!")
}
console.log(password, repeatPassword)
}, [password, repeatPassword])
return (
<div className="registration-form">
<form>
<div>
<input
name="password"
data-name="password"
onChange={(e) => changeValue(e)}
className="password"
type="password"
placeholder="ENTER YOUR PASSWORD HERE"
/>
<div className="animated-button">
</div>
</div>
<div>
<input
id="pwd"
name="repeatPassword"
data-name="repeatPassword"
onChange={(e) => changeValue(e)}
className="repeat-password"
type="password"
placeholder="REPEAT YOUR PASSWORD HERE"
/>
</div>
</div>
</form>
</div>
);
}
export default RegisterBoard;

React error: Cannot read property 'users' of undefined

I'm trying to run this code (picked up from some source) where inputs are created dynamically and values are recorded on submit.
I'm getting this error:
Cannot read property 'users' of undefined while calling createUI.
Can someone help me here, please?
import React, { useState } from "react";
import ReactDOM from "react-dom";
export default function App() {
const [state, setState] = useState({
users: [{ firstName: "", lastName: "" }]
});
const addClick = () => {
setState(prevState => {
users: [...prevState.users, { firstName: "", lastName: "" }];
});
};
const createUI = () => {
state.users.map((el, i) => {
return (
<div key={i}>
<input
placeholder="First Name"
name="firstName"
value={el.firstName || ""}
onChange={handleChange}
/>
<input
placeholder="Last Name"
name="lastName"
value={el.lastName || ""}
onChange={handleChange}
/>
<input type="button" value="remove" onClick={removeClick} />
</div>
);
});
};
const handleChange = (i, e) => {
const { name, value } = e.target;
let users = [...state.users];
users[i] = { ...users[i], [name]: value };
setState({ users });
};
const removeClick = i => {
let users = [...state.users];
users.splice(i, 1);
setState({ users });
};
const handleSubmit = event => {
alert("A name was submitted: " + JSON.stringify(this.state.users));
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
{createUI()}
<input type="button" value="add more" onClick={addClick()} />
<input type="submit" value="Submit" />
</form>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
// const rootElement = document.getElementById("root");
// ReactDOM.render(<App />, rootElement)
Sandbox here ->
https://codesandbox.io/s/dynamic-fields-23cw4?fontsize=14&hidenavigation=1&theme=dark
The reason for that error is the following line:
<input type="button" value="add more" onClick={addClick()} />
Technically you are calling the addClick function which changes the value of your state object. The solution which works fine is the following:
<input type="button" value="add more" onClick={() => addClick()} />
Or shorter way:
<input type="button" value="add more" onClick={addClick} />
I hope that helps!
There were 3 issues with your code,
you executed your onclick handler, addClick which triggered inifinite loop
createUI method did not return the array of created components
addClick function's setState syntax was not correct.
const {useState} = React;
function App() {
const [state, setState] = useState({
users: [{ firstName: "", lastName: "" }]
});
const addClick = () => {
setState(prevState => {
return { users: [...prevState.users, { firstName: "", lastName: "" }] };
});
};
const createUI = () => {
return state.users.map((el, i) => {
return (
<div key={i}>
<input
placeholder="First Name"
name="firstName"
value={el.firstName || ""}
onChange={(e)=>handleChange(e, i)}
/>
<input
placeholder="Last Name"
name="lastName"
value={el.lastName || ""}
onChange={(e)=>handleChange(e, i)}
/>
<input type="button" value="remove" onClick={removeClick} />
</div>
);
});
};
const handleChange = (e, i) => {
const { name, value } = e.target;
let users = [...state.users];
users[i] = { ...users[i], [name]: value };
setState({ users });
};
const removeClick = i => {
let users = [...state.users];
users.splice(i, 1);
setState({ users });
};
const handleSubmit = event => {
alert("A name was submitted: " + JSON.stringify(this.state.users));
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
{createUI()}
<input type="button" value="add more" onClick={addClick} />
<input type="submit" value="Submit" />
</form>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
In addition to #norbiial's answer which should be the accepted answer: Your addClick function is incorrect. Your setState call is not returning anything which means as soon as you click the add button it will break again.
Change to this:
const addClick = () => {
setState(prevState => ({
users: [...prevState.users, { firstName: "", lastName: "" }]
}));
};
The same issue will be seen in createUI.
Error 1:
if you are returning an Object without return statement it should be wrapped in a bracket
const addClick = () => {
setState(prevState => ({
users: [...prevState.users, { firstName: "", lastName: "" }];
}));
};
Error 2:
Missing return statement,
const createUI = () => {
return state.users.map((el, i) => {
return (
<div key={i}>
<input
placeholder="First Name"
name="firstName"
value={el.firstName || ""}
onChange={handleChange}
/>
<input
placeholder="Last Name"
name="lastName"
value={el.lastName || ""}
onChange={handleChange}
/>
<input type="button" value="remove" onClick={removeClick} />
</div>
);
});
};
Error 3:
onClick should have a function, but you are setting a value returned from addClick which is undefined
...
<input type="button" value="add more" onClick={addClick} />
...

How to disable form submit button until all input fields are filled?! ReactJS ES2015

Hi i found an answer to this for a single field form... but what if we have a form with multiple field?
this is fine for disabling it if you have 1 field but it does not work when you want to disable it based on many fields:
getInitialState() {
return {email: ''}
},
handleChange(e) {
this.setState({email: e.target.value})
},
render() {
return <div>
<input name="email" value={this.state.email} onChange={this.handleChange}/>
<button type="button" disabled={!this.state.email}>Button</button>
</div>
}
})
Here is a basic setup for form validation:
getInitialState() {
return {
email: '',
text: '',
emailValid: false, // valid flags for each field
textValid: false,
submitDisabled: true // separate flag for submit
}
},
handleChangeEmail(e) { // separate handler for each field
let emailValid = e.target.value ? true : false; // basic email validation
let submitValid = this.state.textValid && emailvalid // validate total form
this.setState({
email: e.target.value
emailValid: emailValid,
submitDisabled: !submitValid
})
},
handleChangeText(e) { // separate handler for each field
let textValid = e.target.value ? true : false; // basic text validation
let submitValid = this.state.emailValid && textvalid // validate total form
this.setState({
text: '',
textValid: textValid,
submitDisabled: !submitValid
})
},
render() {
return <div>
<input name="email" value={this.state.email} onChange={this.handleChangeEmail}/>
<input name="text" value={this.state.text} onChange={this.handleChangeText}/>
<button type="button" disabled={this.state.submitDisabled}>Button</button>
</div>
}
})
In a more elaborate setup, you may want to put each input field in a separate component. And make the code more DRY (note the duplication in the change handlers).
There are also various solutions for react forms out there, like here.
I would take a little bit different way here...
Instead of setting submitDisabled in every single onChange handler I would hook into lifecycle method to listen to changes.
To be exact into componentWillUpdate(nextProps, nextState). This method is invoked before every change to component - either props change or state change. Here, you can validate your form data and set flag you need - all in one place.
Code example:
componentWillUpdate(nextProps, nextState) {
nextState.invalidData = !(nextState.email && nextState.password);
},
Full working fiddle https://jsfiddle.net/4emdsb28/
This is how I'd do it by only rendering the normal button element if and only if all input fields are filled where all the states for my input elements are true. Else, it will render a disabled button.
Below is an example incorporating the useState hook and creating a component SubmitButton with the if statement.
import React, { useState } from 'react';
export function App() {
const [firstname, setFirstname] = useState('');
const [lastname, setLastname] = useState('');
const [email, setEmail] = useState('');
function SubmitButton(){
if (firstname && lastname && email){
return <button type="button">Button</button>
} else {
return <button type="button" disabled>Button</button>
};
};
return (
<div>
<input value={email} onChange={ e => setEmail(e.target.value)}/>
<input value={firstname} onChange={ e => setFirstname(e.target.value)}/>
<input value={lastname} onChange={ e => setLastname(e.target.value)}/>
<SubmitButton/>
</div>
);
};
This might help. (credits - https://goshakkk.name/form-recipe-disable-submit-button-react/)
import React from "react";
import ReactDOM from "react-dom";
class SignUpForm extends React.Component {
constructor() {
super();
this.state = {
email: "",
password: ""
};
}
handleEmailChange = evt => {
this.setState({ email: evt.target.value });
};
handlePasswordChange = evt => {
this.setState({ password: evt.target.value });
};
handleSubmit = () => {
const { email, password } = this.state;
alert(`Signed up with email: ${email} password: ${password}`);
};
render() {
const { email, password } = this.state;
const isEnabled = email.length > 0 && password.length > 0;
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Enter email"
value={this.state.email}
onChange={this.handleEmailChange}
/>
<input
type="password"
placeholder="Enter password"
value={this.state.password}
onChange={this.handlePasswordChange}
/>
<button disabled={!isEnabled}>Sign up</button>
</form>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<SignUpForm />, rootElement);
export default function SignUpForm() {
const [firstName, onChangeFirstName] = useState("");
const [lastName, onChangeLastName] = useState("");
const [phoneNumber, onChangePhoneNumber] = useState("");
const areAllFieldsFilled = (firstName != "") && (lastName != "") && (phoneNumber != "")
return (
<Button
title="SUBMIT"
disabled={!areAllFieldsFilled}
onPress={() => {
signIn()
}
}
/>
)
}
Similar approach as Shafie Mukhre's!

Categories