React onSubmit are not triggered with some Form.Check checkboxes - reactjs

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.

Related

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

How to show/hide a select input according to a value chosen in a previous select input reactjs?

I am new to reactjs, and here I have a form, and in that form I have an input select with two value options.
And the first value option should allow me to bring up a second input select with these value options, and the second nothing at all.
I made my form and for the first input select I manage to do an onChange method, to retrieve the chosen value, but now how to do a test on the chosen value, to display or not the second input select ?
And how to show or hide this second input select ?
My Form
// methode that retrieve the chosen value in input select
const handleOptionChange = (event: any) => {
console.log(event);
};
const FormContent = (props: any) => {
const { control, handleSubmit, errors } = useForm();
const { Option } = Select;
const onSubmit = handleSubmit((data) => {
console.log(data);
});
return (
<form onSubmit={onSubmit}>
<Row gutter={8}>
<Col md={12} lg={12} sm={24}>
<div className="ant-form-item">
<label className="label">Nom Utilisateur <span className="text-danger">*</span></label>
<Controller
// as={inputField("Nom Utilisateur")}
name="username"
control={control}
defaultValue={""}
rules={{ required: true }}
render={props => (<><Input name={props.name} defaultValue={props.value} className="ant-form-item-control" placeholder="Nom Utilisateur" /></>)}
/>
{errors.username && "First name is required"}
</div>
</Col>
<Col md={12} lg={12} sm={24}>
<div className="ant-form-item">
<label className="label">Mot de passe <span className="text-danger">*</span></label>
<Controller
// as={inputPassField()}
name="password"
control={control}
defaultValue={""}
rules={{ required: true }}
render={props => (<Input.Password placeholder="Mot de passe" />)}
/>
{errors.password && "First name is required"}
</div>
</Col>
</Row>
<Row gutter={8}>
<Col md={12} lg={12} sm={24}>
<div className="ant-form-item">
<label className="label">Profile<span className="text-danger">*</span></label>
<Controller
name="profile"
control={control}
defaultValue={""}
rules={{ required: true }}
render={({ onChange, value, name }) => (
<Select
showSearch
placeholder="Select a person"
onChange={(event) => {
onChange(event)
handleOptionChange(event)
}}
value={value ? value : ""}
// name={name}
optionFilterProp="children"
filterOption={(input, option: any) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}>
<option key="b2b_user" value="B2B_CLIENT">B2B_USER</option>
<option key="app_user" value="APPLICATION_USER">USER_SIMPLE</option>
</Select>)}
/>
{errors.profile && "Profile is required"}
</div>
</Col>
</Row>
<Row gutter={8}>
<Col md={12} lg={12} sm={24}>
<Flex alignItems="center" justifyContent="center">
<Button onClick={() => props.onClose()} icon={<CloseOutlined />} size="small" className="mr-3" type="text">Annuler</Button>
<Button icon={<CheckCircleOutlined />} type='primary' htmlType='submit'>
Valider
</Button>
</Flex>
</Col>
</Row>
</form>);
}
<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>
Second input to show/hide
export const SelectCompanyField = () => {
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(10);
const { data, error } = useSWR<ServerResponse, any>(companyUrls.base + `?page:${page}&perPage:${perPage}`, url => getDataByParams(companyUrls.base, { page: '' + page, perPage: '' + perPage }));
console.log("Data", data, "Error", error);
console.log(data?.entities);
return (
<Select
showSearch
placeholder="Choisir une compagnie"
optionFilterProp="children"
filterOption={(input, option: any) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{data?.entities.map(d => (
<option value={d.index} key={d.id} >
{d.name}
</option>
))}
</Select>
);
};
// the second input select to show/hide
<Col md={24} lg={24} sm={24}>
<div className="ant-form-item">
<label className="label">Compagnie <span className="text-danger">*</span></label>
<Controller
as={SelectCompanyField()}
name="company"
control={control}
defaultValue={""}
rules={{ required: false }}
/>
{errors.company && "Company is required"}
</div>
</Col>
<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>
Thanks
Something like...
const [firstOptionValue, setFirstOptionValue] = useState(null)
const handleOptionChange = (event: any) => {
setFirstOptionValue(event.target.value)
};
Then when you want to conditionally render the second select...
{firstOptionValue && <SecondSelectContainer/>}
So whatever is in SecondSelectContainer will only render if firstOptionValue is not falsey.

How to add edit button and function in react.js

i want to share this question. So, i have a form which is designed by react-bootstrap. And also use React Hooks and React Function Component. I have a form which is add new form and delete form but i don't do edit form.
This is a return statement
return(
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control ref = {firstname} type="text" placeholder="Name.." />
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control ref = {secondname} type="text" placeholder="Surname.." />
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control ref = {email} type="email" placeholder="E-Mail" />
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control ref = {comment} as="textarea" rows={3} placeholder = "Notes :)"/>
</Form.Group>
<Button className = "btn-lg" onClick={handleSubmit} variant="success" type="submit">Submit</Button>
</Form>
</Col>
</Row>
{Formss}
</Container>
)
And then, These are the function of this return
const Formss = input.map((item , index) =>
{
return(
<Lists key = {index} item = {item} index = {index} deleteFunc={handleDelete}/>
)
}
)
const handleSubmit = (event) => {
event.preventDefault();
const name = firstname.current.value
const surname = secondname.current.value
const mail = email.current.value
const mycomment = comment.current.value
const data = {id:id(),
name : name,
surname : surname,
mail : mail,
mycomment : mycomment}
if(data.name && data.surname && data.mail && data.mycomment){
setInput([...input, data])
firstname.current.value = ""
secondname.current.value = ""
email.current.value = ""
comment.current.value =""
}else{
console.log("oopss")
}
}
I use ref hook for handleSubmit. So, How to add edit button and edit function?
To be able to edit data, and to save it in state you can do it as in provided example. Then in handleSubmit function you can process your data further:
import React from "react";
import { Container, Row, Col, Form, Button } from "react-bootstrap";
const App = () => {
const handleSubmit = (e) => {
e.preventDefault();
console.log(state);
};
const initialState = {
firstname: "",
secondname: "",
email: "",
comment: "",
};
const [state, setState] = React.useState(initialState);
const handleChange = ({ target: { value, name } }) => {
setState({ ...state, [name]: value });
};
return (
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control
name="firstname"
value={state.firstname}
type="text"
placeholder="Name.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control
name="secondname"
value={state.secondname}
type="text"
placeholder="Surname.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control
value={state.email}
name="email"
type="email"
placeholder="E-Mail"
onChange={handleChange}
/>
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control
name="comment"
value={state.comment}
as="textarea"
rows={3}
placeholder="Notes :)"
onChange={handleChange}
/>
</Form.Group>
<Button className="btn-lg" variant="success" type="submit">
Submit
</Button>
</Form>
</Col>
</Row>
</Container>
);
};
export default App;

How to have react-datepicker update Formik nested object

So I set up datepicker within my form like so
<FieldArray
name="config"
render={(arrayHelpers) => (
<div>
{values.config.map((config, index) => (
<div key={index}>
...
<DatePicker
name={`config.${index}.date`}
type="date"
value={values.date}
className={
"form-control" +
(errors.date&& touched.date
? " is-invalid"
: "")
}
onChange={(e) =>
setFieldValue("date", e)
}
/>
The data is added to the state but as an additional field instead of updating the initial state within formik. It updates likes this.
{"domain_url":"","schema_name":"","name":"","config":[{"first":"","last":"","email":"","date":""}],"date":"2020-06-10T04:00:00.000Z"}
I would appreciate any ideas.
below is a new edit of the majority of the code.
the datepicker is not displaying the date within the form field but it is updating the state correctly, now I just need it to display correctly within the form and format the date to drop the string at the end
static propTypes = {
addTenant: PropTypes.func.isRequired,
};
onSubmit = (values) => {
values.preventDefault();
this.props.addTenant(values);
};
render() {
const {
domain_url,
schema_name,
name,
config,
} = this.state;
const TenantSchema = Yup.object().shape({
domain_url: Yup.string()
.max(255, "Must be shorter than 255 characters")
.required("Client URL header is required"),
schema_name: Yup.string()
.max(255, "Must be shorter than 255 characters")
.required("Client db name is required"),
name: Yup.string()
.max(255, "Must be shorter than 255 characters")
.required("Client name is required"),
});
return (
<div className={s.root}>
<Formik
initialValues={{
domain_url: "",
schema_name: "",
client_name: "",
config: [
{
date: "",
Tenant_description: "",
},
],
}}
// validationSchema={TenantSchema} this is commented off because it breaks
submittions
onSubmit={(values, { setSubmitting, resetForm }) => {
setSubmitting(true);
values.domain_url = values.domain_url + ".localhost";
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
resetForm();
setSubmitting(false);
}, 100);
}}
>
{({
values,
errors,
status,
touched,
handleBlur,
handleChange,
isSubmitting,
setFieldValue,
handleSubmit,
props,
}) => (
<FormGroup>
<Form onSubmit={handleSubmit}>
<legend>
<strong>Create</strong> Tenant
</legend>
<FormGroup row>
<Label for="normal-field" md={4} className="text-md-right">
Show URL
</Label>
<Col md={7}>
<InputGroup>
<Field
id="appended-input"
name="domain_url"
type="text"
value={values.domain_url}
className={
"form-control" +
(errors.domain_url && touched.domain_url
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="domain_url"
component="div"
className="invalid-feedback"
/>
<InputGroupAddon addonType="append">
.localhost
</InputGroupAddon>
</InputGroup>
</Col>
</FormGroup>
<FormGroup row>
<Label for="normal-field" md={4} className="text-md-right">
Database Name
</Label>
<Col md={7}>
<Field
name="schema_name"
type="text"
className={
"form-control" +
(errors.schema_name && touched.schema_name
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="schema_name"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="normal-field" md={4} className="text-md-right">
Name
</Label>
<Col md={7}>
<Field
name="name"
type="text"
className={
"form-control" +
(errors.name && touched.name
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="name"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
<FieldArray
name="config"
render={(arrayHelpers) => (
<div>
{values.config.map((config, index) => (
<div key={index}>
<FormGroup row>
<Label
md={4}
className="text-md-right"
for="mask-date"
>
Tenant Description
</Label>
<Col md={7}>
<TextareaAutosize
rows={3}
name={`config.${index}.tenant_description`}
id="elastic-textarea"
type="text"
onReset={values.event_description}
placeholder="Quick description of tenant"
onChange={handleChange}
value={values.tenant_description}
onBlur={handleBlur}
className={
`form-control ${s.autogrow} transition-height` +
(errors.tenant_description &&
touched.tenant_description
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="tenant_description"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
<FormGroup row>
<Label
for="normal-field"
md={4}
className="text-md-right"
>
Date
</Label>
<Col md={7}>
<DatePicker
name={`config[${index}]['date']`}
selected={getIn(values, `config[${index}]
['date']`) || ''}
value={getIn(values, `config[${index}]
['date']`) || ''}
onChange={(e) =>
setFieldValue(`config[${index}]['date']`, e);
}
/>
/>
<ErrorMessage
name="date"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
</div>
))}
</div>
)}
/>
<div className="form-group">
<button
type="submit"
disabled={isSubmitting}
className="btn btn-primary mr-2"
>
Save Tenant
</button>
<button type="reset" className="btn btn-secondary">
Reset
</button>
</div>
</Form>
<Col md={7}>{JSON.stringify(values)}</Col>
</FormGroup>
)}
</Formik>
</div>
);
}
}
export default connect(null, { addTenant })(TenantForm);
Change your name,value and onChange as following
import { FieldArray, getIn } from 'formik';
<DatePicker
name={`config[${index}]['date']`}
selected={getIn(values, `config[${index}]['date']`) || ''}
value={getIn(values, `config[${index}]['date']`) || ''}
onChange={(e) =>
setFieldValue(`config[${index}]['date']`, e);
}
/>

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