Formik lost fields when trigger a modal confirm - javascript

I have a form using Formik library, all are right but when i want to confirm and submit i need to pass first a modal, the problem is when i launch the confirm modal all data i put in the form are eliminate and nothing is send, i noticed when the i launch the modal, the form tag are upload and then lost the data, someone has the same problem ? o are something to prevent the form tag upload when change the state of the modal ?
here is part of my code, i use CSSTransition on the modal, that mount and unmount the component, and i call previous fields on the form using FieldArray
<Formik
enableReinitialize
initialValues={INITIAL_VALUES}
onSubmit={(values) => {
this.props.onSubmitForm(values.rows);
}}
>
{({ values, errors, touched, isValid }) => (
<Form>
<Title />
<div className="wrapper__brick wrapper__brick--to-up">
<FieldArray
name="rows"
render={({ push }) => (
<>
<div className="wrapper__block">
<div className="master-table">
<FieldArray
name="rows"
render={({ remove }) => (
<div className="master-table__container">
{values.rows.length > 0 &&
values.rows.map((rows, index) => (
<div
className="master-table__row"
key={index}
>
<div className="master-table__item">
<Field
className={errors.rows && errors.rows[index] && touched.rows && touched.rows[index] ?
'input input--empty is-danger'
:
'input input--empty'
}
name={`rows.${index}.name`}
placeholder="Name"
type="text"
validate={validateName}
/>
<ErrorMessage
name={`rows.${index}.name`}
component="p"
className="help is-danger"
/>
</div>
<div className="master-table__item">
<div className={rows.default ? 'select select--disabled' : 'select select--empty'}>
<Field
as="select"
disabled={rows.default}
name={`rows.${index}.kind`}
>
{this.allowedKinds.map((row) => (
<option
value={row.internal}
key={row.internal}
>
{row.name}
</option>
))}
</Field>
</div>
</div>
<div className="master-table__item">
<button
className="button button--trigger tooltip is-tooltip-right"
data-tooltip={rows.default ? t('common.deleteNotAvailable') : t('common.delete')}
onClick={() => remove(index)}
type="button"
disabled={rows.default}
>
<span className="icon">
<i className="far fa-trash-alt" />
</span>
</button>
</div>
</div>
))}
</div>
)}
/>
</div>
</div>
<Footer
onAddRow={() => push({
id: UUID.v4(),
name: '',
kind: 'string',
type: 'generic',
required: false,
default: false
})}
validForm={!isValid}
/>
<TransitionWrapper stateToggle={this.state.openModal}>
<ModalDialog
iconModal="fas fa-info-circle"
titleText={t('modals.descriptionContinue')}
onCloseMethod={this.handleShowModal}
onAcceptMethod={this.props.onSubmitForm}
/>
</TransitionWrapper>
</>
)}
/>
</div>
</Form>
)}
</Formik>

Related

Edit User Details using React

I am stuck on editing user details and updating it.
What I'm trying to accomplish is when I click on "update" button, I can edit their name and email. And I can also delete the entry by clicking the "delete" button.
I have added the ability to add new User which I am able to code.
This is my code: https://codesandbox.io/s/zen-browser-5ifrel?file=/src/User.js
How do I add a if-else statement in my render so that IF i click on "update" button on one of the entry (e.g., id === selected.id), it will transform the "name" and "email" to textboxes to allow for edit. And 2 buttons for them to "confirm" their update or "cancel" their update.
render() {
return (
<div className="App">
{
this.state.users.map((u) => {
return (
<React.Fragment key={u._id}>
<div className="box">
<h3>{u.name}</h3>
<h4>{u.email}</h4>
<button onClick={() => {
this.beginEdit(u);
}}
>Update
</button>
<button onClick={() => {
this.deleteUser(u);
}}
>Delete
</button>
</div>
</React.Fragment>
);
})}
{this.renderAddUser()}
</div>
);
}
Use conditional rendering.
render() {
return (
<div className="App">
{
this.state.users.map((u) => {
return (
<React.Fragment key={u._id}>
<div className="box">
{u.isEditing ? (
<React.Fragment>
<input type="text" placeholder="name" />
<input type="text" placeholder="email" />
</React.Fragment>
) : (
<React.Fragment>
<h3>{u.name}</h3>
<h4>{u.email}</h4>
</React.Fragment>
)}
<button onClick={() => {
this.beginEdit(u);
}}
>Update
</button>
<button onClick={() => {
this.deleteUser(u);
}}
>Delete
</button>
</div>
</React.Fragment>
);
})}
{this.renderAddUser()}
</div>
);
}
You can probably figure out the rest.
you can use this that render output depends on the condition of (id === selectedUser.id)
state = {
selected = null;
}
render() {
return (
<div className="App">
{this.state.users.map((user) => {
return (
<div className="box" >
{selected?.id === user?._id ? (
<>
<input type="text" placeholder="name" defaultValue={user.name} />
<input type="text" placeholder="email" defaultValue={user.email} />
<button onClick={() => { this.handleCancel(user);}}>
Cancel
</button>
<button onClick={() => { this.handleConfirm(user);}}>
Confirm
</button>
</>
) : (
<>
<h3>{user.name}</h3>
<h4>{user.email}</h4>
<button onClick={() => { this.beginEdit(user);}}>
Update
</button>
<button onClick={() => { this.deleteUser(user);}}>
Delete
</button>
</>
)}
</div>
);
})}
{this.renderAddUser()}
</div>
);
}

Formik API : send different value in handleSubmit based on button click

I have the following code of a child component which is sending the form values to the parent when a user clicks .
Save and Continue button
Submit button
The Save and Continue button in the code is defined as follows:
<div className="form-field">
<Button size="large" variant="contained" color="primary" style={{marginLeft: '5px'}} type="submit">Save & Continue</Button>
</div>
When a user clicks Save and Continue button, I want to return requestStatuses: props.SimpleRequest && props.SimpleRequest.statusId || '10',.
However, when a user clicks the following Submit button:
<Button size="large" variant="contained" color="primary"
type="submit">Submit</Button>
I want to return props.SimpleRequest && props.SimpleRequest.statusId || '6',.
The default value for Status is 6 when a user interacts with the form and the dropdown is disabled so user can't change it. However, I want to send different values of it as I explained above based on different button clicks. Is it possible?
Minimal Code with relavent Formik form information is below:
const SimpleRequestForm = (props) => {
const {values, setFieldValue, touched, errors, isSubmitting, handleReset, handleChange} =
props;
const growl = React.createRef()
return (
<div>
<div id="formDiv">
<Growl ref={growl}/>
<Form className="form-column-3">
<div className="SimpleRequest-form">
<div className="form-field">
<CustomSelectField name="requestStatuses" disabled type="select" placeholder="Status"/>
</div>
<div className="form-field">
<CustomSelectField name="requestPrioritieses" type="select" value='Normal' placeholder="Priority"/>
</div>
<div className="form-field">
<CustomSelectField name="assignees" type="select" placeholder="Assignee"/>
</div>
<div className="form-field">
<Button size="large" variant="contained" color="primary" style={{marginLeft: '5px'}} type="submit">Save & Continue</Button>
</div>
</div>
<div className="btn-group-right">
<Button size="large" variant="contained" color="primary"
type="submit">Submit</Button>
<Button size="large" variant="contained" color="primary" onClick={handleReset}
style={{marginLeft: '5px'}} type="button">Reset</Button>
<Button size="large" variant="contained" color="primary" onClick={props.onCancel}
style={{marginLeft: '5px'}} type="button">Cancel</Button>
</div>
</Form>
</div>
</div>
)
};
export const SimpleRequestEnhancedForm = withFormik(
{
mapPropsToValues: props => {
return {
requestId: props.SimpleRequest && props.SimpleRequest.requestId || '',
requestStatuses: props.SimpleRequest && props.SimpleRequest.statusId || '6',
requestPrioritieses: props.SimpleRequest && props.SimpleRequest.priorityId || '3',
assignees: props.SimpleRequest && props.SimpleRequest.assigneeId || '',
}
},
validationSchema:validationSchema,
handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
console.log("submit Simple Request Form....")
values.assets = JSON.parse(sessionStorage.getItem('uploadedFiles'));
props.handleSubmit(values)
setSubmitting(false)
},
setFieldValue(field, value, shouldVal) {
console.log('In setFieldValue')
},
displayName: 'Simple Request Form',
})(SimpleRequestForm)

Cannot enter value into MDEditor

When I run the program, I can't enter a value in the input, help me
const FormCommnent = ({ onChange, onSubmit, value }) => (
<div className="form-comment">
<MDEditor
value={value}
onChange={onChange}
name="content"
rows={4}
autoFocus={0}
preview='edit'
/>
<MDEditor.Markdown source={value} />
<Button htmlType="submit" onClick={onSubmit} >
Add Comment
</Button>
</div>
);

when I try to type something in the form field, It doesn't let me type anything

I need to do a form in react.js but when I try to type something in the form field, It doesn't let me type anything. I create a function for the input e my form. what am i doing wrong? please help me. thanks.
renderInput(title, value, onChange, validateField, placeholder) {
return (
<div className="col-12 col-md-4">
<div className="form-groud">
<label>{title}</label>
<input type="text" className="form-control"
name={title}
value={value}
onChange={e => onChange(e)}
onBlur={validateField}
placeholder={placeholder} />
</div>
</div>
)
}
renderForm() {
return (
<div className="form">
<div className="row">
{this.renderInput("Avatar", this.state.member.avatar, e => this.updateField(e), this.validateField, "profile picture" )}
{this.renderInput("Name", this.state.member.name, e => this.updateField(e), this.validateField, "name" )}
{this.renderInput("Email", this.state.member.email, e => this.updateField(e), this.validateField, "email" )}
{this.renderInput("Project", this.state.member.project, e => this.updateField(e), this.validateField, "project" )}
{this.renderInput("Devices", this.state.member.devices, e => this.updateField(e), this.validateField, "devices" )}
{this.renderInput("MainStack", this.state.member.mainstack, e => this.updateField(e), this.validateField,"main stack" )}
</div>
<hr />
<div className="row">
<div className="col-12 d-flex justify-content-end">
<button className="btn btn-primary"
onClick={e => this.save(e)}>
Save
</button>
<button className="btn btn-secondary ml-2"
onClick={e => this.clear(e)}>
Cancel
</button>
</div>
</div>
</div>
)
}
My updateField method:
updateField (event) {
const member = {...this.state.member}
member[event.target.avatar] = event.target.value
member[event.target.name] = event.target.value
member[event.target.project] = event.target.value
member[event.target.devices] = event.target.value
member[event.target.mainstack] = event.target.value
this.setState({ member })
}
you should controll input form value's using react state, in React is called a “controlled component”. So check your updateField function and make sure that it change the state value.
https://reactjs.org/docs/forms.html

React useState and map()

I'm trying to make an comment input from map,
but since I use the same useState all the input fields get changed.
How can I target a specific input?
return (
<div>
{posts.map(post => (
<div key={post.id}>
<img
src={`https://localhost:1111/api/posts/uploads/images/${post.content}`}
alt={`${post.id}`}
/>
<p>{post.description}</p>
<span>{post.likes ? post.likes : 0}</span>
<button onClick={() => like(post.id)}>Like</button>
<Link to={`/post/${post.id}`}>Edit</Link>
<button onClick={() => deletePost(post.id)}>Delete</button>
<form onSubmit={uploadComment}>
<input
type="text"
onChange={handleComment}
value={comment}
placeholder="Comment"
/>
</form>
</div>
))}
</div>
)
You have an own state per rendered post, which means that it is a use case for an own component:
function Post(post, deletePost) {
const [comment, setComment] = useState('');
const uploadComment = () => {}; // your code is missing
return (
<div key={post.id}>
<img
src={`https://localhost:1111/api/posts/uploads/images/${post.content}`}
alt={`${post.id}`}
/>
<p>{post.description}</p>
<span>{post.likes ? post.likes : 0}</span>
<button onClick={() => like(post.id)}>Like</button>
<Link to={`/post/${post.id}`}>Edit</Link>
<button onClick={() => deletePost(post.id)}>Delete</button>
<form onSubmit={uploadComment}>
<input
type="text"
onChange={e => setComment(e.target.value)}
value={comment}
placeholder="Comment"
/>
</form>
</div>
)
}
Then your render function would look like this:
return (
<div>
{posts.map(post => <Post post={post} deletePost={deletePost} />)}
</div>
)
Consider using react useState hook per input.

Categories