Ternary Operator in Button causes '...' expected TS(1005) error - reactjs

I am using a ternary operator in button and facing '...' expected, TS(1005) error. The syntax in question is exactly as provided in the reactjs website. (example:1)
(Example: 1)
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
My Code is:
import React, { useState } from 'react'
import Button from 'react-bootstrap/Button'
import Form from 'react-bootstrap/Form'
import Modal from 'react-bootstrap/Modal'
import { Link } from 'react-router-dom'
export default function LoginSignupModal() {
const [show, setShow] = useState(false)
const handleClose = () => setShow(false)
const handleShow = () => setShow(true)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [errorPassword, setErrorPassword] = useState(false)
function handleRegister() {
console.log("name", name)
}
function handlePasswordConfirmation(data) {
if (data.target.value != password) {
console.log("didn't match")
setErrorPassword(true)
} else {
console.log("matched")
setErrorPassword(false)
}
}
return (
<>
<Button variant="primary" onClick={handleShow} style={{ marginLeft: '5px' }}>
Signup
</Button>
<Modal
show={show}
onHide={handleClose}
backdrop="static"
keyboard={false}
>
<Modal.Header closeButton>
<Modal.Title>Registration Form</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group controlId="signupName">
<Form.Label>Name</Form.Label>
<Form.Control value={name} onChange={(data) => setName(data.target.value)} placeholder="John Doe" />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control value={email} onChange={(data) => setEmail(data.target.value)} type="email" placeholder="xyz#email.com" />
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control value={password} onChange={(data) => setPassword(data.target.value)} type="password" placeholder="Password" />
</Form.Group>
<Form.Group controlId="formBasicPasswordConfirmation">
<Form.Label>Confirm Password</Form.Label>
<Form.Control type="password" onChange={(data) => handlePasswordConfirmation(data)} placeholder="Re-enter Password" />
</Form.Group>
<-- **ERROR IN THE FOLLOWING LINE** -->
<Button variant="primary" type="submit" {(errorPassword) ? "disabled" : "active"}>Register</Button>
<Button variant="secondary" onClick={handleClose} style={{ marginLeft: "5px" }}>Close</Button>
</Form>
</Modal.Body>
<Modal.Footer>
By signing up, you agree to our privacy policy and terms and conditions.
</Modal.Footer>
</Modal>
</>
);
}
Here I am trying to add disabled/active on a button depending on errorPassword state. but it's giving me an error.
Error generating code part:
<Button variant="primary" type="submit" {(errorPassword) ? "disabled" : "active"}>Register</Button>

disabled and active are separate boolean props, those variants should work:
// Recommended
<Button disabled={errorPassword} active={!errorPassword}>
Register
</Button>
// Unreadable
<Button {...{ [errorPassword ? "disabled" : "active"]: true }}>
Register
</Button>
// Same as above just a bit more readable
const errorPasswordProps = { [errorPassword ? "disabled" : "active"]: true };
<Button {...errorPasswordProps}>Register</Button>;

This is how material set its ternity in its source-code
<Button {...(errorPassword ? { disabled: true } : { active: true })}>
Register
</Button>
but the better way to express this would be to define hasError property in Button itself and pass hasError={errorPassword}

Related

Why do i get error 400 on my graphQL mutation create user

I'm working with Reactjs and GraphQL integration. i got a problem when i'm doing mutation for new user.
Scenario :
Creating user using Modals bootstrap. when successful create new user, it shows alert or information success.
Code :
Here's my ModalCreate component code.
import React, { useState, useEffect } from 'react';
import { Button, Modal, Form } from "react-bootstrap";
const ModalCreate = (props) => {
// state for check input component
const [value, setValue] = useState({
username: props.username || '',
email: props.email || '',
fullname: props.full_name || '',
password: props.password || '',
phone: props.phone || '',
address: props.address || '',
groupid: props.group_id,
});
const onChange = event => {
setValue({
...value,
[event.target.name]: event.target.value
})
}
useEffect(() => {
if (props.show) {
document.body.classList.add("modal-open");
}
return () => {
if (document.body.classList.contains("modal-open")) {
document.body.classList.remove("modal-open");
}
};
}, [props.show]);
return (
<Modal show={props.show}>
<Modal.Header>
<Modal.Title> <span>FORMULIR AKUN PENGGUNA</span> </Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={e => {
e.preventDefault();
props.action({
variables: {
...value
}
})
}}>
<Form.Group className="mb-3">
<Form.Label>Role Akun</Form.Label>
<Form.Select aria-label="pilih user role" value={value.groupid} onChange={onChange}>
<option value="superadmin">Super Admin</option>
<option value="admin">Admin</option>
<option value="admin_rj ">Admin RJ</option>
</Form.Select>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Username</Form.Label>
<Form.Control name="username" value={value.username} onChange={onChange}/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Nama Lengkap</Form.Label>
<Form.Control name="fullname" value={value.fullname} onChange={onChange}/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Email</Form.Label>
<Form.Control type="email" name="email" value={value.email} onChange={onChange}/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Password</Form.Label>
<Form.Control type="password" name="password" value={value.password} onChange={onChange}/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Phone</Form.Label>
<Form.Control type="text" name="phone" value={value.phone} onChange={onChange}/>
</Form.Group>
<Button variant="secondary" type='submit'>
Simpan
</Button>
</Form>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={props.onClose}>
Keluar
</Button>
</Modal.Footer>
</Modal>
);
};
export default ModalCreate;
and action/performing mutation in page call index.js :
import React, { useState } from 'react';
import { useQuery, useMutation } from '#apollo/client';
import { Container, Card, Button, InputGroup, FormControl, Form, Spinner } from 'react-bootstrap';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faSearch } from '#fortawesome/fontawesome-free-solid';
import CardInfo from '../../../component/PengaturanPengguna/CardInfo';
import TableUserInfo from '../../../component/PengaturanPengguna/Table';
import { Loading } from '../../../component/Common';
import ModalCreate from '../../../component/PengaturanPengguna/Modals/ModalCreate';
import { GET_ALL_USERS, GET_USER_BY_ID } from '../../../gql/query';
import { REGISTER_USER } from '../../../gql/mutation';
const SearchInput = () => {
return (
<InputGroup className="mb-3">
<InputGroup.Text>
<FontAwesomeIcon icon={faSearch} />
</InputGroup.Text>
<FormControl
type="text"
placeholder="Search..."
/>
</InputGroup>
)
}
const PengaturanPengguna = (props) => {
// refetch and query data
const { data: usersdata, loading: usersloading, error: userserror } = useQuery(GET_ALL_USERS);
const { refetch, loading } = useQuery(GET_ALL_USERS);
// show modals
const [showModal, setShowModal] = useState(false);
// mutation new register user
const [registerUser, { loading: registerloading, error: registererror }] = useMutation(REGISTER_USER, {
refetchQueries: [{ query: GET_USER_BY_ID }, { query: GET_ALL_USERS }],
onCompleted: data => {
console.log(data)
},
onError: err => {
console.error(err);
}
}) ;
const handleRefreshClick = () => {
refetch();
}
const handleShowModal = () => setShowModal(true);
const handleCloseModal = () => setShowModal(false);
if (usersloading || registerloading) return <Loading/>
if (userserror || registererror) return <p>Error!</p>
return (
<Container>
<CardInfo/>
<Card>
<Card.Title>
<span className='base-md text-regular mt-2 std-txt-primary-200'>Data Pengguna Dashboard</span>
</Card.Title>
<Card.Body>
<div className='d-flex justify-content-between'>
<Form inline>
<SearchInput/>
<Button variant='secondary' onClick={handleRefreshClick} disabled={loading}>{loading ? ( <Spinner
as="span"
animation="border"
size="sm"
role="status"
aria-hidden="true"/> ) : 'Muat Ulang'}</Button>
</Form>
<div>
<Button variant='success' onClick={() => { setShowModal(true) }}>Daftar Akun</Button>
</div>
</div>
<TableUserInfo users={usersdata}/>
</Card.Body>
</Card>
{
showModal ? <ModalCreate show={handleShowModal} onClose={handleCloseModal} action={registerUser} /> : null
}
</Container>
)
}
export default PengaturanPengguna;
and here's my mutation :
const REGISTER_USER = gql`
mutation($input: RegisterInput!) {
register(input: $input) {
username
email
full_name
phone
address
group_id
}
}
`;
Error :
I got this error
Also, Network Status Tabs :
I've been try any solution but it still not working, any help will be appreciated, thank you
If you are getting validation error from apollo for required fields then check the form fields may be name attribute is missing and value is not storing inside your state.

Reactjs Modal Form Submission with MySql (axios & sequelize)

Good Day,
I have a header outline with both Login and Sign Up Modal. At the moment I am working on the Sign Up Modal where for now I can insert a new User but I want to display another Modal to confirm signup successful as well as close the Sign Up Modal. Also to display error messages via Modal. Here is the outline of my header Code so far. along with the Authentication Controller Class.
AUTHENTICATION CODE
import { Op } from 'sequelize'
import bcryptjs from 'bcryptjs'
import jwt from 'jsonwebtoken'
import UsersModel from "../models/users_model.js"
export const register = (request, response, next) => {
const name = request.body.name
const surname = request.body.surname
const salt = bcryptjs.genSaltSync(10)
const passcode = bcryptjs.hashSync(request.body.passcode, salt)
const username = request.body.username
const email = request.body.email
UsersModel.findOrCreate({
where: { [Op.or]: [ { username }, { email } ] },
defaults: { name, surname, username, email, passcode }
}).then((created) => {
if (!created) return response.status(404).json('User exists')
else return response.status(200).json(created)
}).catch((error) => {
return response.status(500).json(error)
})
}
HEADER CODE
import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Modal, CloseButton, Form, Row, Col, FloatingLabel, ModalBody } from 'react-bootstrap'
import 'bootstrap/scss/bootstrap.scss'
import axios from 'axios'
import './Header.scss'
function LoginModal(modal) {
return (
<>
<Modal {...modal} size={'lg'} aria-labelledby={'contained-modal-title-vcenter'} centered>
<Modal.Header closeButton={CloseButton}>
<Modal.Title>Login Panel</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form action='/' method={'POST'}>
<Form.Group className='mb-3' controlId='formBasicEmail'>
<Row className='align-items-center'>
<Col xs={'auto'}>
<FloatingLabel controlId='floatingInput' label='Username' className='mb-3'>
<Form.Control type={'text'} name={'username'} placeholder={'Type Username'} id={'username'} />
</FloatingLabel>
</Col>
<Col xs={'auto'}>
<FloatingLabel controlId='floatingInput' label='Passcode' className='mb-3'>
<Form.Control type={'password'} name={'passcode'} placeholder={'Type Passcode'} id={'passcode'} />
</FloatingLabel>
</Col>
</Row>
</Form.Group>
<Button variant={'primary'} type={'submit'}>Submit</Button>
</Form>
</Modal.Body>
<Modal.Footer>
<Button onClick={modal.onHide}>Close</Button>
</Modal.Footer>
</Modal>
</>
)
}
function RegisterModal(modal) {
const [inputs, dataSet] = useState({
name: '',
surname: '',
username: '',
email: '',
passcode: ''
})
const [ error, setError] = useState(null)
const navigate = useNavigate()
const dataEntry = (event) => {
dataSet((previous) => ({...previous, [event.target.name]: event.target.value }))
}
const dataSubmit = async (event) => {
event.preventDefault()
try {
await axios.post('auth/register/', inputs)
navigate('/')
} catch (error) {
setError(error.response.data)
}
}
return (
<>
<Modal {...modal} size={'lg'} aria-labelledby={'contained-modal-title-vcenter'} centered>
<Modal.Header closeButton={CloseButton}>
<Modal.Title>Sign Up</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Row className='mb-3'>
<Form.Group as={Col} controlId='formGridName'>
<Form.Label>Name</Form.Label>
<Form.Control type={'text'} name={'name'} placeholder={'Type Name'} id={'name'} onChange={dataEntry} />
</Form.Group>
<Form.Group as={Col} controlId='formGridSurname'>
<Form.Label>Surname</Form.Label>
<Form.Control type={'text'} name={'surname'} placeholder={'Type Surname'} id={'surname'} onChange={dataEntry} />
</Form.Group>
</Row>
<Row className='mb-3'>
<Form.Group as={Col} controlId='formGridEmail'>
<Form.Label>Email</Form.Label>
<Form.Control type={'email'} name={'email'} placeholder={'Type Email'} onChange={dataEntry} />
</Form.Group>
<Form.Group as='mb-3' controlId='formGridUsername'>
<Form.Label>Username</Form.Label>
<Form.Control type={'text'} name={'username'} placeholder={'Enter Userame'} id={'username'} onChange={dataEntry} />
</Form.Group>
<Form.Group as='mb-3' controlId='formGridPasscode'>
<Form.Label>Passcode</Form.Label>
<Form.Control type={'password'} name={'passcode'} placeholder={'Enter Passcode'} id={'passcode'} onChange={dataEntry} />
</Form.Group>
<Form.Group as='mb-3' controlId='formGridConfirm'>
<Form.Label>Passcode</Form.Label>
<Form.Control type={'password'} name={'confirm'} placeholder={'Confirm Passcode'} id={'confirm'} />
</Form.Group>
</Row>
<Form.Group as='mb-3' controlId='formGridSubmit'>
<Button variant={'primary'} type={'submit'} onClick={dataSubmit} >Submit</Button>
</Form.Group>
<Modal>
<ModalBody>{error && {error} }</ModalBody>
</Modal>
</Form>
</Modal.Body>
<Modal.Footer>
<Button onClick={modal.onHide}>Close</Button>
</Modal.Footer>
</Modal>
</>
)
}
export default function Header() {
const [loginModal, setLoginModal] = useState(false)
const [registerModal, setRegisterModal] = useState(false)
return (
<>
<header className='main-header'>
<nav className='nav-content'>
<ul className='nav-content-list'>
<li className='nav-content-item'>
<Button variant='primary' onClick={() => setLoginModal(true)}>Login</Button>
</li>
<li className='nav-content-item'>
<Button variant='primary' onClick={() => setRegisterModal(true)}>Sign Up</Button>
</li>
</ul>
</nav>
</header>
<LoginModal show={loginModal} onHide={() => setLoginModal(false)} />
<RegisterModal show={registerModal} onHide={() => setRegisterModal(false)} />
</>
)
}

React app hanging when typing on input with onChange state

When I start typing anything in the input fields, the page hangs and nothing gets typed. It was working fine before, it just started happening suddenly. I don't know what went wrong.
I have tried adding onBlur and the problem persists. I tried adding value={registerEmail} in the input fields and the problem still remains as well.
Pleae check :(
import React, {useState} from 'react'
import {
createUserWithEmailAndPassword,
onAuthStateChanged,
signInWithEmailAndPassword,
signOut
} from 'firebase/auth'
import { Form, Button, Card, Container } from 'react-bootstrap'
import {auth} from '../../services/firebase-config'
export default function SignUp() {
const [registerEmail, setRegisterEmail] = useState("")
const [registerPassword, setRegisterPassword] = useState("")
const [registerConfirmedPassword, setRegisterConfirmedPassword] = useState("")
const [user, setUser] = useState({})
onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser)
})
const register = async (event) => {
event.preventDefault();
try {
const user = await createUserWithEmailAndPassword(auth, registerEmail, registerPassword)
console.log(user)
}
catch(error) {
//accounts that don't exist
console.log(error.message)
}
}
const login = async(event) => {
event.preventDefault();
try {
const user = await signInWithEmailAndPassword(auth, registerEmail, registerPassword)
console.log(user)
}
catch(error) {
//accounts that don't exist
console.log(error.message)
}
}
const logout = async(event) => {
try {
await signOut(auth)
}
catch(error) {
console.log(error.message)
}
}
return (
<Container className="d-flex align-items-center justify-content-center w-100">
<Card className='p-3' style={{maxWidth:"400px"}}>
<Card.Body>
<h2 className='text-center mb-4'>Sign Up</h2>
<Form>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" onChange={e => setRegisterEmail(e.target.value)} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" onChange={e => setRegisterPassword(e.target.value)} required />
</Form.Group>
<Form.Group id="password-confirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control type="password" onChange={e => setRegisterConfirmedPassword(e.target.value)} required />
</Form.Group>
{ <Button className='w-100' onClick={(e) => register(e)}>Sign Up</Button>}
</Form>
</Card.Body>
<div className='w-100 text-center mt-2'>
Already have an account? <Button className='w-100' onClick={(e) => login(e)}>Login</Button>
</div>
<Button onClick={(e) => logout(e)}>Logout</Button>
</Card>
</Container>
)
}
Value attr and Initial state was missing in the form.control
<Form>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control value={registerEmail} type="email" onChange={e => setRegisterEmail(e.target.value)} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" value={registerPassword} onChange={e => setRegisterPassword(e.target.value)} required />
</Form.Group>
<Form.Group id="password-confirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control type="password" onChange={e => setRegisterConfirmedPassword(e.target.value)} required />
</Form.Group>
{ <Button className='w-100' onClick={(e) => register(e)}>Sign Up</Button>}
</Form>
Example - codesandbox

react-hook useFormInput() form validation not working

Link to code sandbox https://stackblitz.com/edit/react-cdv6mx?devtoolsheight=33&file=src/ResetPassword.js
EXPLANATION: When the user enters incorrect details, the server sends 400: bad request error with a message which can be seen in the Response tab under the network's tab. The intention is to validate the form fields before submitting the form and display an error message(s) if incorrect fields are entered. Also, the intention is to disable to reset the button until the form fields match the criteria. So, that will prevent the user from accidentally submitting half-entered fields.
I have a functional component in which I have a simple form.
PROBLEM: I am calling validatForm() method on onChange. The method should first check that the newPassword and confirmPassword are the same and are as per the password rules(requirements) and if true, only then, send the data.
UPDATED CODE IS IN THE STACKBLITZ LINK ABOVE.
I am use useFormInput() like below
const email = useFormInput("");
const newPassword = useFormInput("");
const confirmPassword = useFormInput("");
and I have written a useFormInput() method
const useFormInput = (initialValue) => {
const [value, setValue] = useState(initialValue);
const handleChange = (e) => {
setValue(e.target.value);
};
return {
value,
onChange: handleChange,
};
};
and a validateForm() method and I am passing it my <button/>
/* Your password must contain at least one capital letter, one
*number and one lowercase letter, and it must contain at least 8
*characters*/
const validateForm = (event) => {
let pass = event.target.value;
let reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/;
let test = reg.test(pass);
if (test) {
this.setState({ value: event.target.value });
} else {
alert("password validation unsuccessful. Please try again.");
return;
}
};
and in render()
<FormGroup row>
<Label for="Email" sm={2}>
Email
</Label>
<Col sm={4}>
<Input
type="email"
name="email"
id="Email"
{...email}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="newPassword" sm={2}>
New Password
</Label>
<Col sm={4}>
<Input
type="password"
name="password"
id="newPassword"
{...newPassword}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="confirmPassword" sm={2}>
Confirm Password
</Label>
<Col sm={4}>
<Input
type="password"
name="confirmPassword"
id="confirmPassword"
{...confirmPassword}
/>
</Col>
</FormGroup>
<div className="form-actions">
{error && (
<>
<small style={{ color: "red" }}>{error}</small>
<br />
</>
)}
<br />
<Col lg={{ offset: 2 }} sm={{ size: 1 }}>
<Button
className="mail-reset-btn"
block
type="submit"
value={loading ? "Loading..." : "Login"}
onClick={handleReset}
disabled={!validateForm}
>
Reset
</Button>
</Col>
</div>
</Form>
Update your validateForm to destructure the password fields from the form onSubmit event. Create an errors object to track what field errors there are. If the errors object is empty then validation passes, otherwise set error state.
const validateForm = event => {
event.preventDefault();
const { confirmPassword, newPassword } = event.target;
const errors = {};
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/;
if (!regex.test(newPassword.value)) {
errors.requirementUnmet = "New password does not meet requirements.";
}
if (newPassword.value !== confirmPassword.value) {
errors.passwordMismatch = "Entered passwords do not match.";
}
if (!Object.keys(errors).length) {
alert("password validation successful.");
setError(null);
return;
}
setError(errors);
};
Attach validateForm to the form's onSubmit handle.
<Form onSubmit={validateForm}>
Ensure you've a type="submit" button in the form.
<Button
className="mail-submit-btn"
block
type="submit"
value={loading ? "Loading..." : "Login"}
>
Submit
</Button>
Updated stackblitz (though I've not an account so copying updated code below.)
Note: I simply JSON.stringify(error) the error for simplicity, but you'll want to render this more gracefully.
Entire ResetPassword.js
import React, { useState } from "react";
import {
Button,
Form,
FormGroup,
Input,
Col,
Label,
Modal,
ModalHeader,
ModalBody,
ModalFooter
} from "reactstrap";
const useFormInput = initialValue => {
const [value, setValue] = useState(initialValue);
const handleChange = e => {
setValue(e.target.value);
};
return {
value,
onChange: handleChange
};
};
const ResetPassword = props => {
// form inputs
const email = useFormInput("");
const newPassword = useFormInput("");
const confirmPassword = useFormInput("");
// using hooks
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [modal, setModal] = useState(false);
const toggle = () => setModal(!modal);
const validateForm = event => {
event.preventDefault();
const { confirmPassword, newPassword } = event.target;
const errors = {};
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/;
if (!regex.test(newPassword.value)) {
errors.requirementUnmet = "New password does not meet requirements.";
}
if (newPassword.value !== confirmPassword.value) {
errors.passwordMismatch = "Entered passwords do not match.";
}
if (!Object.keys(errors).length) {
alert("password validation successful.");
setError(null);
return;
}
setError(errors);
};
const handleReset = e => {
e.preventDefault();
setError(null);
setLoading(true);
// some unrelated redux code
};
return (
<div className="mail-reset" id="forgotPassword">
<div className="mail-reset-content">
<Form onSubmit={validateForm}>
<h3 className="form-title">Enter Information</h3>
<FormGroup row>
<Label for="Email" sm={2}>
Email
</Label>
<Col sm={4}>
<Input
type="email"
name="email"
id="Email"
placeholder="Email"
aria-label="email address"
aria-describedby="email address"
aria-invalid="false"
{...email}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="newPassword" sm={2}>
New Password
</Label>
<Col sm={4}>
<Input
type="password"
name="password"
id="newPassword"
placeholder="New Password"
aria-label="new password"
aria-describedby="new password"
aria-invalid="false"
{...newPassword}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="confirmPassword" sm={2}>
Confirm Password
</Label>
<Col sm={4}>
<Input
type="password"
name="confirmPassword"
id="confirmPassword"
placeholder="Confirm Password"
aria-label="new password"
aria-describedby="new password"
aria-invalid="false"
{...confirmPassword}
/>
</Col>
</FormGroup>
<div className="modal-wrapper">
<Col sm={{ size: 4, offset: 2 }}>
<Button onClick={toggle} className="passwordReqBtn">
Password Requirements
</Button>
</Col>
<Modal isOpen={modal} toggle={toggle} className="mail-reset-modal">
<ModalHeader toggle={toggle}>Password Requirements</ModalHeader>
<ModalBody>
Your password must contain at least one capital letter, one
number and one lowercase letter, and it must contain at least 8
characters
</ModalBody>
<ModalFooter>
<Button onClick={toggle} className="btn-modal pull-right">
OK
</Button>{" "}
</ModalFooter>
</Modal>
</div>
<div className="form-actions">
{error && (
<>
<small style={{ color: "red" }}>{JSON.stringify(error)}</small>
<br />
</>
)}
<br />
<Col lg={{ offset: 2 }} sm={{ size: 1 }}>
<Button
className="mail-reset-btn"
block
type="submit"
value={loading ? "Loading..." : "Login"}
>
Submit
</Button>
<Button
className="mail-reset-btn"
block
type="reset"
value={loading ? "Loading..." : "Login"}
onClick={handleReset}
>
Reset
</Button>
</Col>
</div>
</Form>
</div>
</div>
);
};
export default ResetPassword;

Pass form data to modal component React/Boostrap

I have a modal component and form component. I am trying to pass the data using React hooks from the form back to the modal. I am having trouble doing this. Here is what I have so far -
Modal(Parent)
interface ISystem {
systemName: string;
allowNumber: number;
statusCode: string;
createdBy?: string;
createdDate?: string;
}
const ModalForm = (props) => {
const { buttonLabel, className } = props;
const [modal, setModal] = useState(false);
const toggle = () => setModal(!modal);
const addButtonHandler = () => {
toggle();
console.log(FORM DATA SHOULD BE HERE)
};
return (
<div>
<Button color="primary" onClick={toggle}>
{buttonLabel}
</Button>
<Modal
isOpen={modal}
toggle={toggle}
className={className}
centered
size="lg"
>
<ModalHeader toggle={toggle}>{buttonLabel}</ModalHeader>
<ModalBody>
<AddSystem></AddSystem>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={addButtonHandler}>
Add
</Button>{" "}
<Button color="secondary" onClick={toggle}>
Cancel
</Button>
</ModalFooter>
</Modal>
</div>
);
};
export default ModalForm;
This is my Form component
const AddSystem = (props) => {
const [systemId, setSystemId] = useState("");
const [systemName, setSystemName] = useState("");
const [allowNumber, setAllowNumber] = useState("");
const [statusCode, setStatusCode] = useState("");
const [lastModifiedBy, setLastModifiedBy] = useState("");
const submitHandler = (event) => {
event.preventDefault();
};
return (
<Fragment>
<Form onSubmit={submitHandler} className="mx-auto">
<Form.Group as={Row} controlId="systemId">
<Form.Label column sm="2">
{" "}
ID{" "}
</Form.Label>
<Col sm="10">
<Form.Control
type="text"
name="systemId"
placeholder="Leave blank for new system"
value={systemId}
disabled
onChange={(event) => setSystemId(event.target.value)}
/>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="systemName">
<Form.Label column sm="2">
{" "}
Systen Name{" "}
</Form.Label>
<Col sm="10">
<Form.Control
type="text"
name="systemName"
placeholder=""
value={systemName}
onChange={(event) => setSystemName(event.target.value)}
/>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="allowNumber">
<Form.Label column sm="2">
{" "}
Allow Number{" "}
</Form.Label>
<Col sm="10">
<Form.Control
as="select"
name="allowNumber"
value={allowNumber}
onSelect={(event) => setAllowNumber(event.target.value)}
>
<option>Choose...</option>
{["1", "2", "3", "4", "5"].map((opt) => (
<option>{opt}</option>
))}
</Form.Control>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="statusCode">
<Form.Label column sm="2">
{" "}
Status Code{" "}
</Form.Label>
<Col sm="10">
<Form.Control
as="select"
name="statusCode"
value={statusCode}
onSelect={(event) => setStatusCode(event.target.value)}
>
<option>Choose...</option>
{["Active", "Draft"].map((opt) => (
<option>{opt}</option>
))}
</Form.Control>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="lastModifiedBy">
<Form.Label column sm="2">
{" "}
Last Modified By{" "}
</Form.Label>
<Col sm="10">
<Form.Control
type="text"
name="lastModifiedBy"
placeholder=""
value={lastModifiedBy}
disabled
onChange={(event) => setLastModifiedBy(event.target.value)}
/>
</Col>
</Form.Group>
</Form>
</Fragment>
);
};
export default AddSystem;
I don't want to have the button inside the form. The button needs to stay in the modal footer but somehow receive information from the form...This is so that the modal can become re-usable and have any type of form passed into it perhaps

Resources