Reactjs Modal Form Submission with MySql (axios & sequelize) - reactjs

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)} />
</>
)
}

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.

React onSubmit are not triggered with some Form.Check checkboxes

I have written modal window with dynamic fields. Text input, date and radio boxes works fine, but when I`m trying to use checkbox inputs it falls.
handleSubmit does not work and not goes into method body
AnswerQuestion:
function AnswerQuestion(props) {
const {questionStore} = useContext(Context);
const dispatch = useNotification();
const question = questionStore.getActiveAnswer();
const show = props.show;
const handleClose = props.handleClose;
const handleUpdate = props.handleUpdate;
const [checkedState, setCheckedState] = useState(question.id && question.answerEntity.answerType === "CHECKBOX"
? Array(question.answerEntity.options.length).fill(false)
: []
)
useEffect(() => {
if(question.id && question.answerEntity.answerType === "CHECKBOX") {
const newCheckedState = question.answerEntity.options.map((option) => question.answerEntity.answer.includes(option));
setCheckedState(newCheckedState);
}
}, [])
const setInitialValues = () => {
if (question.id) {
return {
author: question.author.username,
question: question.question,
answerType: question.answerEntity.answerType,
options: question.answerEntity.options,
date: question.answerEntity.answerType === "DATE" && question.answerEntity.answer ? new Date(question.answerEntity.answer) : new Date(),
answer: question.answerEntity.answer ? question.answerEntity.answer : "",
};
} else {
return {
author: "",
question: "",
answerType: "",
options: "",
date: new Date(),
answer: "",
};
}
};
const schema = yup.object().shape({
author: yup.string().required(),
question: yup.string().required(),
answer: yup.string(),
answerCheckBox: yup.array(),
date: yup.date(),
});
const submit = (values) => {
questionStore
.answerActiveQuestion(question.answerEntity.answerType, values.answer, values.date)
.then(() => handleUpdate());
handleClose();
dispatch({
type: "SUCCESS",
message: "Your answer was saved.",
title: "Success"
})
}
return (
<Formik
enableReinitialize
render={(props) => {
return (
<AnswerQuestionForm
{...props}
show={show}
handleClose={handleClose}
checkedState={checkedState}
></AnswerQuestionForm>
);
}}
initialValues={setInitialValues()}
validationSchema={schema}
onSubmit={submit}
>
</Formik>
)
}
And AnswerQuestionForm:
function AnswerQuestionForm(props) {
const {
values,
errors,
touched,
handleSubmit,
handleChange,
handleClose,
setFieldValue,
setFieldTouched,
show,
checkedState,
} = props;
function insertAnswerModule() {
switch (values.answerType) {
case "DATE":
return (
<Col sm={9}>
<DatePicker
name="date"
value={Date.parse(values.date)}
selected={values.date}
className="form-control"
onChange={(e) => {
setFieldValue('date', e);
setFieldTouched('date');
}}
/>
</Col>
)
case "SINGLE_LINE_TEXT":
return (
<Col sm={9}>
<Form.Control
type="text"
name="answer"
value={values.answer}
onChange={handleChange}
isValid={touched.question && !errors.question}
isInvalid={!!errors.question}
/>
<Form.Control.Feedback type="invalid">
{errors.question}
</Form.Control.Feedback>
</Col>
)
case "MULTILINE_TEXT":
return (
<Col sm={9}>
<Form.Control as="textarea" rows={3}
type="text"
name="answer"
value={values.answer}
onChange={handleChange}
isValid={touched.question && !errors.question}
isInvalid={!!errors.question}
/>
<Form.Control.Feedback type="invalid">
{errors.question}
</Form.Control.Feedback>
</Col>
)
case "CHECKBOX":
return (
<Col sm={9}>
{values.options.map((option, id) => (
<Form.Check
id={id}
type="checkbox"
name="answerCheckBox"
label={option}
value={option}
defaultChecked={checkedState[id]}
onChange={handleChange}
/>
))}
</Col>
)
case "RADIO_BUTTON":
return (
<Col sm={9}>
{values.options.map((option) => (
<Form.Check
type="radio"
name="answer"
label={option}
value={option}
checked={option === values.answer}
onChange={handleChange}
/>
))}
</Col>
)
}
}
return (
<Modal show={show} onHide={handleClose} centered backdrop="static">
<Modal.Header closeButton>
<Modal.Title>Answer the question</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Row className="me-3 md-3 justify-content-between">
<Form.Group as={Row}>
<Form.Label column sm={3}>
From user
</Form.Label>
<Col sm={9}>
<Form.Control
type="text"
name="author"
value={values.author}
readOnly
disabled
></Form.Control>
</Col>
</Form.Group>
</Row>
<Row className="me-3 mt-3 md-3 justify-content-between">
<Form.Group as={Row}>
<Form.Label column sm={3}>
Question
</Form.Label>
<Col sm={9}>
<Form.Control
type="text"
name="question"
value={values.question}
readOnly
disabled
></Form.Control>
</Col>
</Form.Group>
</Row>
<Row className="me-3 mt-3 md-3 justify-content-between">
<Form.Group as={Row}>
<Form.Label column sm={3}></Form.Label>
{insertAnswerModule()}
</Form.Group>
</Row>
</Form>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleSubmit}>
SAVE
</Button>
</Modal.Footer>
</Modal>
)
}
I would be glad to know where is error and how to solve it.
SOLUTION:
I passed answer as string[] if answerType is "CHECKBOX". It`s not allowed in HTML and i changed answer type to string and it begins to work.

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

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

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}

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