I am having troubles with my code and can't find a solution to it, basically i'm trying to clone a card element when clicking on a 'plus' button, to 'add a member'. I am working with react-redux.
I wanna be able to add two other members (no more) with different datas in each of them which is why I have done three, so this is what I got in my store:
team :[{
Firstname: "",
Age: "",
Role: "",
Statut: "",
Money: "",
Formation: 0,
Experience: 0,
Reseau: 0,
Rating: 0,
},
{
Firstname1: "",
Age1: "",
Role1: "",
Statut1: "",
Money1: "",
Formation1: 0,
Experience1: 0,
Reseau1: 0,
Rating1: 0,
},
{
Firstname2: "",
Age2: "",
Role2: "",
Statut2: "",
Money2: "",
Formation2: 0,
Experience2: 0,
Reseau2: 0,
Rating2: 0,
}
]
And this is what is in my component (the <link>/<button> is at the very end of the code):
class TeamEditor extends Component{
render() {
return(
// BACKGROUND CARD //
<div className="mr-2">
<Card className= "Editor-card">
<Row>
<Col md={4}>
<CardHeader className="card-header-warning card-header-icon">
<div className="card-icon card-icon-team">
<img src={process.env.PUBLIC_URL + '../assets/images/001-trade.svg' } width="40px" className="icon" alt="icon"/>
</div>
<h3 className="float-left card-category mt-2"><span className="text-team">Notre équipe</span></h3>
</CardHeader>
</Col>
<Col md={8} >
<NavLink to="/" className="d-flex justify-content-end mt-0">
<Button className= "mt-3">Enregistrer et quitter</Button>
</NavLink>
</Col>
</Row>
{/* CARD NUMBER ONE */}
<Card className="InsideCard">
<CardBody>
<Form>
<Row className="d-flex justify-content-around">
<Col md={2}>
<FormGroup>
<Label for="examplePrenom">Mon Prénom</Label>
<Input type="Prenom" name="Prenom" id="examplePrenom" value={this.props.Firstname} onChange={this.props.setFirstname}/>
</FormGroup>
</Col>
<Col md={1}>
<FormGroup>
<Label for="examplePassword">Mon âge</Label>
<Input type="Age" name="Age" id="exampleAge" value={this.props.Age} onChange={this.props.setAge} />
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="exampleFonction">Ma fonction</Label>
<Input type="Fonction" name="Fonction" id="exampleFonction" value={this.props.Role} onChange={this.props.setRole} />
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label className="labelForm" for="StatutSocial">Mon statut</Label>
<Input type="select" name="StatutSocial" id="StatutSocial" value={this.props.Statut} onChange={this.props.setStatut}>
<option>Actionnaire</option>
<option>Gérant.e ou co Gérant.e</option>
<option>Salarié.e</option>
<option>Soutien</option>
</Input>
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="Finance">Mes attentes financière</Label>
<Input type="Finance" name="Attente Financiere" id="Finance" value={this.props.Money} onChange={this.props.setMoney}/>
</FormGroup>
</Col>
</Row>
</Form>
<Row className="d-flex justify-content-around mt-3" >
<p className= "Passion">Passion</p>
<p className= "Passion">Expérience</p>
<p className= "Passion">Réseau</p>
<p className= "Passion">Formation</p>
</Row>
<Row className="d-flex justify-content-around">
<ReactStars value={this.props.Passion} onChange={this.props.setPassion} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Experience} onChange={this.props.setExperience} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Reseau} onChange={this.props.setReseau} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Formation} onChange={this.props.setFormation} count={4} size={20} color2={'#ffd700'} />
</Row>
</CardBody>
</Card>
{/* CARD NUMBER TWO */}
<Card className="InsideCard">
<CardBody>
<Form>
<Row className="d-flex justify-content-around">
<Col md={2}>
<FormGroup>
<Label for="examplePrenom">Mon Prénom</Label>
<Input type="Prenom" name="Prenom" id="examplePrenom" value={this.props.Firstname1} onChange={this.props.setFirstname1}/>
</FormGroup>
</Col>
<Col md={1}>
<FormGroup>
<Label for="examplePassword">Mon âge</Label>
<Input type="Age" name="Age" id="exampleAge" value={this.props.Age1} onChange={this.props.setAge1} />
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="exampleFonction">Ma fonction</Label>
<Input type="Fonction" name="Fonction" id="exampleFonction" value={this.props.Role1} onChange={this.props.setRole1} />
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label className="labelForm" for="StatutSocial">Mon statut</Label>
<Input type="select" name="StatutSocial" id="StatutSocial" value={this.props.Statut1} onChange={this.props.setStatut1}>
<option>Actionnaire</option>
<option>Gérant.e ou co Gérant.e</option>
<option>Salarié.e</option>
<option>Soutien</option>
</Input>
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="Finance">Mes attentes financière</Label>
<Input type="Finance" name="Attente Financiere" id="Finance" value={this.props.Money1} onChange={this.props.setMoney1}/>
</FormGroup>
</Col>
</Row>
</Form>
<Row className="d-flex justify-content-around mt-3" >
<p className= "Passion">Passion</p>
<p className= "Passion">Expérience</p>
<p className= "Passion">Réseau</p>
<p className= "Passion">Formation</p>
</Row>
<Row className="d-flex justify-content-around">
<ReactStars value={this.props.Passion1} onChange={this.props.setPassion1} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Experience1} onChange={this.props.setExperience1} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Reseau1} onChange={this.props.setReseau1} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Formation1} onChange={this.props.setFormation1} count={4} size={20} color2={'#ffd700'} />
</Row>
</CardBody>
</Card>
{/* CARD NUMBER THREE */}
<Card className="InsideCard">
<CardBody>
<Form>
<Row className="d-flex justify-content-around">
<Col md={2}>
<FormGroup>
<Label for="examplePrenom">Mon Prénom</Label>
<Input type="Prenom" name="Prenom" id="examplePrenom" value={this.props.Firstname2} onChange={this.props.setFirstname2}/>
</FormGroup>
</Col>
<Col md={1}>
<FormGroup>
<Label for="examplePassword">Mon âge</Label>
<Input type="Age" name="Age" id="exampleAge" value={this.props.Age2} onChange={this.props.setAge2} />
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="exampleFonction">Ma fonction</Label>
<Input type="Fonction" name="Fonction" id="exampleFonction" value={this.props.Role2} onChange={this.props.setRole2} />
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label className="labelForm" for="StatutSocial">Mon statut</Label>
<Input type="select" name="StatutSocial" id="StatutSocial" value={this.props.Statut2} onChange={this.props.setStatut2}>
<option>Actionnaire</option>
<option>Gérant.e ou co Gérant.e</option>
<option>Salarié.e</option>
<option>Soutien</option>
</Input>
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="Finance">Mes attentes financière</Label>
<Input type="Finance" name="Attente Financiere" id="Finance" value={this.props.Money2} onChange={this.props.setMoney2}/>
</FormGroup>
</Col>
</Row>
</Form>
<Row className="d-flex justify-content-around mt-3" >
<p className= "Passion">Passion</p>
<p className= "Passion">Expérience</p>
<p className= "Passion">Réseau</p>
<p className= "Passion">Formation</p>
</Row>
<Row className="d-flex justify-content-around">
<ReactStars value={this.props.Passion2} onChange={this.props.setPassion2} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Experience2} onChange={this.props.setExperience2} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Reseau2} onChange={this.props.setReseau2} count={4} size={20} color2={'#ffd700'} />
<ReactStars value={this.props.Formation2} onChange={this.props.setFormation2} count={4} size={20} color2={'#ffd700'} />
</Row>
</CardBody>
</Card>
</Card>
<Row className="d-flex justify-content-around">
+
</Row>
</div>
);
}
}
const mapActionToProps = {
//CARD NUMBER ONE//
setFirstname : setFirstname,
setAge: setAge,
setRole: setRole,
setStatut: setStatut,
setMoney: setMoney,
setPassion: setPassion,
setExperience: setExperience,
setReseau: setReseau,
setFormation: setFormation,
//CARD NUMBER TWO//
setFirstname1 : setFirstname1,
setAge1: setAge1,
setRole1: setRole1,
setStatut1: setStatut1,
setMoney1: setMoney1,
setPassion1: setPassion1,
setExperience1: setExperience1,
setReseau1: setReseau1,
setFormation1: setFormation1,
//CARD NUMBER THREE//
setFirstname2 : setFirstname2,
setAge2: setAge2,
setRole2: setRole2,
setStatut2: setStatut2,
setMoney2: setMoney2,
setPassion2: setPassion2,
setExperience2: setExperience2,
setReseau2: setReseau2,
setFormation2: setFormation2,
}
const mapStateToProps = state => ({
//CARD NUMBER ONE//
team: state.team,
Firstname : state.team.Firstname,
Age : state.team.Age,
Role: state.team.Role,
Statut: state.team.Statut,
Money: state.team.Money,
Passion: state.team.Passion,
Experience: state.team.Experience,
Reseau: state.team.Reseau,
Formation: state.team.Formation,
//CARD NUMBER TWO//
Firstname1 : state.team.Firstname1,
Age1 : state.team.Age1,
Role1: state.team.Role1,
Statut1: state.team.Statut1,
Money1: state.team.Money1,
Passion1: state.team.Passion1,
Experience1: state.team.Experience1,
Reseau1: state.team.Reseau1,
Formation1: state.team.Formation1,
//CARD NUMBER THREE//
Firstname2 : state.team.Firstname2,
Age2 : state.team.Age2,
Role2: state.team.Role2,
Statut2: state.team.Statut2,
Money2: state.team.Money2,
Passion2: state.team.Passion2,
Experience2: state.team.Experience2,
Reseau2: state.team.Reseau2,
Formation2: state.team.Formation2
}
);
export default connect(mapStateToProps, mapActionToProps)(TeamEditor);
I do not know what to put in my constructor, neither on my button (link).
Answering all your questions. You don't need constructor unless you make some computations on parent class or on received props before class creation. Look carefuly at your code - you don't see yet difference between props received from global state and local state, but to make minimal changes I will only explain the difference - local component state is when there is no need to share it with other components, so storing this in state, than copy to store, than send it to props is not right. Rather use initial state in reducer and in connect method skip first argument connect(undefined, ....
Look also at mapDispatchToProps method - this should be function, not an object, unless newest redux allows it, it's function because you may need some computations before passing it to global state (store), same idea for mapStateToProps.
class TeamEditor extends Component {
/* no need for state (state is not the same as props) and without constructor
you can write state = {here your local state}; no need for 'this' keyword
*/
state = {
Team: [],
//...other initial parameters
};
//better use arrow function - no need to use .bind in constructor
render = () => {
return (<div className="mr-2">
{this.props.team.map(t => (<Card className="Editor-card">
<Row>
<Col md={4}>
<CardHeader className="card-header-warning card-header-icon">
<div className="card-icon card-icon-team">
<img src={process.env.PUBLIC_URL + '../assets/images/001-trade.svg'} width="40px" className="icon"
alt="icon"/>
</div>
<h3 className="float-left card-category mt-2"><span className="text-team">Notre équipe</span></h3>
</CardHeader>
</Col>
<Col md={8}>
<NavLink to="/" className="d-flex justify-content-end mt-0">
<Button className="mt-3">Enregistrer et quitter</Button>
</NavLink>
</Col>
</Row>
<Card>
<CardBody>
<Form>
<Row className="d-flex justify-content-around">
<Col md={2}>
<FormGroup>
<Label for="examplePrenom">Mon Prénom</Label>
<Input type="Prenom" name="Prenom" id="examplePrenom" value={t.Firstname}
onChange={this.props.setFirstname}/>
</FormGroup>
</Col>
<Col md={1}>
<FormGroup>
<Label for="examplePassword">Mon âge</Label>
<Input type="Age" name="Age" id="exampleAge" value={t.Age} onChange={this.props.setAge}/>
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="exampleFonction">Ma fonction</Label>
<Input type="Fonction" name="Fonction" id="exampleFonction" value={t.Role}
onChange={this.props.setRole}/>
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label className="labelForm" for="StatutSocial">Mon statut</Label>
<Input type="select" name="StatutSocial" id="StatutSocial" value={t.Statut}
onChange={t.setStatut}>
<option>Actionnaire</option>
<option>Gérant.e ou co Gérant.e</option>
<option>Salarié.e</option>
<option>Soutien</option>
</Input>
</FormGroup>
</Col>
<Col md={2}>
<FormGroup>
<Label for="Finance">Mes attentes financière</Label>
<Input type="Finance" name="Attente Financiere" id="Finance" value={t.Money}
onChange={t.setMoney}/>
</FormGroup>
</Col>
</Row>
</Form>
<Row className="d-flex justify-content-around mt-3">
<p className="Passion">Passion</p>
<p className="Passion">Expérience</p>
<p className="Passion">Réseau</p>
<p className="Passion">Formation</p>
</Row>
<Row className="d-flex justify-content-around">
<ReactStars value={t.Passion} onChange={this.props.setPassion} count={4} size={20} color2={'#ffd700'}/>
<ReactStars value={t.Experience} onChange={this.props.setExperience} count={4} size={20} color2={'#ffd700'}/>
<ReactStars value={t.Reseau} onChange={this.props.setReseau} count={4} size={20} color2={'#ffd700'}/>
<ReactStars value={t.Formation} onChange={this.props.setFormation} count={4} size={20} color2={'#ffd700'}/>
</Row>
</CardBody>
</Card>
</Card>
)
)}
<Row className="d-flex justify-content-around">
<a href="ajout" className="round-button" onClick={
// no idea what method should be here but Team seems o be an object not method
}>+</a>
</Row>
</div>
);
};
}
const mapDispatchToProps = (dispatch) => ({
setFirstname: (/* parameters for this action */) => dispatch(setFirstname(/* parameters for this action */)),
setAge: (/* parameters for this action */) => dispatch(setAge(/* parameters for this action */)),
setRole: (/* parameters for this action */) => dispatch(setRole(/* parameters for this action */)),
setStatut: (/* parameters for this action */) => dispatch(setStatut(/* parameters for this action */)),
setMoney: (/* parameters for this action */) => dispatch(setMoney(/* parameters for this action */)),
setPassion: (/* parameters for this action */) => dispatch(setPassion(/* parameters for this action */)),
setExperience: (/* parameters for this action */) => dispatch(setExperience(/* parameters for this action */)),
setReseau: (/* parameters for this action */) => dispatch(setReseau(/* parameters for this action */)),
setFormation: (/* parameters for this action */) => dispatch(setFormation(/* parameters for this action */)),
});
const mapStateToProps = state => ({
Team: state.team,
Firstname: state.team.Firstname,
Age: state.team.Age,
Role: state.team.Role,
Statut: state.team.Statut,
Money: state.team.Money,
Passion: state.team.Passion,
Experience: state.team.Experience,
Reseau: state.team.Reseau,
Formation: state.team.Formation
});
export default connect(mapStateToProps, mapDispatchToProps)(TeamEditor);
Related
Hey guys ı have some issues react hook form handle submit function doesn't work what is issue can you help ?
const AccountTabs = ({ userDetail }) => {
const { register, handleSubmit } = useForm();
console.log(userDetail)
const onSubmit = (data) => {
alert(JSON.stringify(data));
console.log(data)
}
return (
<Fragment>
<Card>
<CardHeader className='border-bottom'>
<CardTitle tag='h4'>İşletme Ayarları</CardTitle>
</CardHeader>
<CardBody className='py-2 my-25'>
<div className='d-flex'>
<div className='me-25'>
<img className='rounded me-50' alt='İşletmeye ait logo ' height='100' width='100' />
</div>
<div className='d-flex align-items-end mt-75 ms-1'>
<div>
<Button tag={Label} className='mb-75 me-75' size='sm' color='primary'>
Yükle
<Input type='file' hidden accept='image/*' />
</Button>
<Button className='mb-75' color='secondary' size='sm' outline >
Sil
</Button>
<p className='mb-0'> JPG veya PNG türünde yükleme yapınız</p>
</div>
</div>
</div>
<Form className='mt-2 pt-50' onSubmit={(e) => { e.preventDefault(); handleSubmit(onSubmit) }} >
<Row>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Ad Soyadı </Label>
<Input defaultValue={userDetail.name} {...register("name", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Kullanıcı adı </Label>
<Input defaultValue={userDetail.username} {...register("kullanici", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > E-mail </Label>
<Input type='email' defaultValue={userDetail.contact.email} {...register("email", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > İşletme Adı </Label>
<Input defaultValue={userDetail.companyName} {...register("companyName", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Telefon Numarası </Label>
<Cleave
value={userDetail.contact.phone}
{...register("phone", { required: true })}
className='form-control'
options={{ phone: true, phoneRegionCode: 'TR' }}
/>
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Adres</Label>
<Input defaultValue={userDetail.contact.address} {...register("address", { required: true })} />
</Col>
<Col className='mt-2' sm='12'>
<input type='submit' className='me-1' value='Kaydet' />
</Col>
</Row>
</Form>
</CardBody>
</Card>
</Fragment>
)
}
export default AccountTabs
form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library, form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library,form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library
handleSubmit fires submit function only when validation is successful, So please see if all the required data is filled when you submit the form ( or handle the validations).
const AccountTabs = ({ userDetail }) => {
const { register, handleSubmit, formState } = useForm();
console.log(userDetail)
const onSubmit = (data) => {
alert(JSON.stringify(data));
console.log(data)
}
// formstate has the errors
console.log(formState.errors);
return (
<Fragment>
//code
</Fragment>
)
}
Check this link for validtions
I am using FormItem as the app UI table filter condition, and using Row and Col to layout the component. Current I am facing a problem that when user scale the window, the FormItem could not auto fit the screen resize. So I want to make the FormItem flexiable, when user scale the broswer window, the FormItem could auto rearrangement to multiline to fit the screen change automatically. This is the code current I am using:
renderSimpleForm() {
const {
form,
dispatch,
loading,
activityM: { wordItems = [] },
activityM,
} = this.props;
const { getFieldDecorator } = form;
const {
formValues: { goodWord },
} = this.state;
return (
<Form onSubmit={this.handleSearch} layout="inline">
<Row gutter={16} justify="start">
<Col md={5} sm={24}>
<FormItem label="create date:">
{getFieldDecorator('activityCreateTime', {
})(<RangePicker className={styles.rangepicker} format={dateFormat} />)}
</FormItem>
</Col>
<Col md={5} sm={24}>
<FormItem label="activity date:">
{getFieldDecorator('activityTime', {
})(<RangePicker className={styles.rangepicker} format={dateFormat} />)}
</FormItem>
</Col>
<Col md={3} sm={24}>
<FormItem label="activity status:">
{getFieldDecorator('activityStatus', {
initialValue: '',
})(
<Select placeholder="please choose" style={{ width: 85 }} onSelect={this.onChoseHouse}>
<Option value="">all</Option>
{getSelectOptionByArr(questionType)}
</Select>
)}
</FormItem>
</Col>
<Col md={4} sm={24}>
<FormItem label="user:">
{getFieldDecorator('name', {
initialValue: this.state.formValues.name,
rules: [{ required: false }],
})(<Input type="text" placeholder="creator" />)}
</FormItem>
</Col>
<Col md={2} sm={20}>
<Button type="primary" shape="round" htmlType="submit" className="fun-button">
search
</Button>
</Col>
</Row>
</Form>
);
}
what should I do to make the FormItem items flexiable?
I define different size with different devcie right now like this with each col:
<Col xs={24} sm={12} md={12} lg={12} xl={8} xxl={5}>
<FormItem label="create date:">
{getFieldDecorator('activityCreateTime', {
})(<RangePicker className={styles.rangepicker} format={dateFormat} />)}
</FormItem>
</Col>
A have some form field that is on the Normal Page and on a Modal, i want the Modal button to trigger the submit event. Whenever i use the submit type="submit" on the Modal button, i get no resposnse. But if i use it in the Normal page button it works. Please what's going on, can't i use it in the Modal.
<Formik
initialValues={{
productName: "",
productNumber: "",
quantity: 1,
unitCost: 0,
totalCost: 0,
customerName: "",
customerNumber: "",
amount: "",
}}
onSubmit={(data, { setSubmitting }) => {
setSubmitting(true);
setTimeout(() => {
console.log(data);
alert(JSON.stringify(data, null, 2));
setSubmitting(false);
}, 2000);
}}
>
{({
values,
handleBlur,
handleChange,
setFieldValue,
isSubmitting,
}) => (
<Form>
<Box>
<Grid templateColumns="repeat(2, 1fr)" gap={5}>
<Box>
<FormLabel>Product Name:</FormLabel>
<Field
as={Input}
name="productName"
type="text"
placeholder="Product Name:"
/>
</Box>
<Box>
<FormLabel>Product Number:</FormLabel>
<Field
as={Input}
name="productNumber"
type="number"
placeholder="Product Number:"
/>
</Box>
<Box>
<FormLabel>Quantity:</FormLabel>
<Field
as={Input}
name="quantity"
type="number"
value={values.quantity}
onChange={handleChange}
onBlur={handleBlur}
placeholder="Quantity:"
/>
</Box>
<Box>
<FormLabel>Unit Cost:(in Naira)</FormLabel>
<Field
as={Input}
name="unitCost"
type="number"
value={values.unitCost}
onChange={handleChange}
onBlur={handleBlur}
placeholder="Unit Cost:"
/>
</Box>
<Box>
<FormLabel>Total Cost:(in Naira)</FormLabel>
<CalculatedField
type="number"
name="totalCost"
values={values}
value={values.totalCost}
setFieldValue={setFieldValue}
onChange={handleChange}
onBlur={handleBlur}
/>
</Box>
</Grid>
<Button mt={4} colorScheme="green" onClick={openIt} isFullWidth >
// If used here, it will work... but i don't want to use it here
Order Now
</Button>
</Box>
<Modal closeOnOverlayClick={true} isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Modal Title</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Box>
<Grid templateColumns="repeat(2, 1fr)" gap={5}>
<Box>
<FormLabel>Customer Name: </FormLabel>
<Field
as={Input}
name="customerName"
type="text"
placeholder="Customer Name:"
/>
</Box>
<Box>
<FormLabel>Customer Number: </FormLabel>
<Field
as={Input}
name="customerNumber"
type="text"
placeholder="Customer Number:"
/>
</Box>
<Box>
<FormLabel>Amount: </FormLabel>
<Field
as={Input}
name="amount"
type="text"
placeholder="Amount:"
/>
</Box>
</Grid>
</Box>
</ModalBody>
<ModalFooter>
<Button colorScheme="green" type="submit" >
// i want to use it here
Pay Now
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</Form>
)}
</Formik>
I don't really understand what you want exactly, but if you want to trigger the submit, you could do with your normal button.
First of all, pass submitForm or handleSubmit as props with your others ones
{({
submitForm or handleSubmit,
values,
handleBlur,
handleChange,
setFieldValue,
isSubmitting,
}) => (
Then on your butotn, remove the type submit and add an event handler on click
<Button colorScheme="green" onClick={submitForm // or handleSubmit}>
Pay Now
</Button>
Im sorry i don't know 100% which one will work, it's been a while im not using React an formik.
But remember, when something not working like you want, try to thing another way to do it. Typically trigger the submit manually with an event handler
So this may be something simple but I'm hitting a roadblock. I want to take in a form input but can't seem to figure out how to append the value correctly so its appending string is captured.
I'm using Formik with yup in react.
<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>
Any help would be appreciated. I just want to get the .localhost to be automatically added to the input items. for this field. I thought I could do something like value=({values.domain_url} + ".localhost") but that didn't seem to work and as you may already tell I am very new to javascript.
Thank you!
Full code below, I'm also having issues with datepicker displaying within the formik state, and then there's how to even get the values to push to my getTenant(function) to be passed to my api.
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);
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
resetForm();
setSubmitting(false);
}, 100);
}}
//onSubmit={onSubmit}
>
{({
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}
onSubmit={(values) => {
values.domain_url = values.domain_url + ".localhost";
}} //this isn't working
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
tag={Field}
name={`config.${index}.date`}
type="date"
selected={values.date}
value={values.date}
className={
"form-control" +
(errors.date&& touched.date
? " is-invalid"
: "")
}
onChange={(e) =>
setFieldValue("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);
You could use setFieldValue if you want to customize the value
https://jaredpalmer.com/formik/docs/api/formik#setfieldvalue-field-string-value-any-shouldvalidate-boolean--void
You can add onChange
<Field
id="appended-input"
name="domain_url"
type="text"
value={values.domain_url}
onChange={st => {
let value = st.target.value;
let suffix = ".localhost";
let index = value.indexOf(".localhost");
if (index > 0) {
suffix = "";
}
//add suffix 'localhost' if it is not already added
props.setFieldValue("domain_url", value + suffix);
}}
className={
"form-control" +
(errors.domain_url && touched.domain_url ? " is-invalid" : "")
}
/>;
But adding suffix is more preferable on onSubmit:
onSubmit = {(values, actions) => {
console.log('valuesbefore',values)
values.domain_url= values.domain_url+ ".localhost"
console.log('valuesafter',values)
this.props.addTenant(values);
};
So I am trying to populate a form with data from my server. The server is returning just fine. All strings. I want each form field to be populated with the current details from the database.
I tried the following:
setting each state function in useEffect, but this wouldn't allow me
to change form data
setting a default value but this only works for one instance of the
form and then changes back
function Dashboard(props) {
const { classes } = props;
let user = firebase.getCurrentUser();
let id = user.uid;
const [profile, setProfileData] = useState('');
useEffect( () => {
axios.get('https://www.memento-wedding.com/user/' + id)
.then(response => {
setProfileData(response.data);
})
console.log(profile.gender);
});
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('');
const [date, setDate] = useState('');
const [gender, setGender] = useState();
return (
<div className="form">
<h1 className="white center">Welcome, {firebase.getCurrentUsername()}!</h1>
<h1 className="white center">Create a Profile</h1>
<Form onSubmit={e => e.preventDefault() && false}>
<Row form>
<Label for="firstName" sm={3} className="white right">First Name</Label>
<Col sm={6}>
<Input type="text" name="firstName" id="name" value={firstName} onChange={e=>setFirstName(e.target.value)}/>
</Col>
<Col sm={1}></Col>
</Row>
<br></br>
<Row form>
<Label for="firstName" sm={3} className="white right">Last Name</Label>
<Col sm={6}>
<Input type="text" name="firstName" id="name" value={lastName} onChange={e=>setLastName(e.target.value)}/>
</Col>
<Col sm={1}></Col>
</Row>
<br></br>
<Row form>
<Label for="email" sm={3} className="white right">Email</Label>
<Col sm={6}>
<Input type="email" name="email" id="email" disabled value={profile.email}/>
</Col>
</Row>
<br></br>
<Row form>
<Label for="birthday" sm={3} className="white right">Birthday</Label>
<Col sm={6}>
<Input type="date" name="date" id="date" value={date} onChange={e=>setDate(e.target.value)}/>
</Col>
</Row>
<br></br>
<Row>
<Label for="gender" sm={3} className="white right">Gender</Label>
<Col md={5} sm={7}>
<RadioButtons gender={gender} setGender={e=>setGender(e.target.value)} />
</Col>
</Row>
</Form>
)
}
Please add filter condition []
useEffect( () => {
axios.get('https://www.memento-wedding.com/user/' + id)
.then(response => {
setProfileData(response.data);
})
console.log(profile.gender);
},[]);