I have a form with two fields name and age. I know when user fill these two fields and hit the submit button I can get the values for these two fields.
But what I want is, I have a button call show filled values. When your press that button I want to see the user-filled values in the form. For example, if he fills name as 'Tom' and age as 85. I want to see that. But right now what I am getting is the empty initial values object.
My Code
How do I achieve this using Reactjs?
U can get the filled fields using Formiks props provided by the Formik.
The values prop provided by the formik will gives the filled fields values. Initially it will be the empty object . After you start filling the fields, the values object will be updated accordingly.
To know more What Props can Formik provide ?
visit :- https://formik.org/docs/api/formik#touched--field-string-boolean-
Hope the below code snippet will be useful for you.
<Formik
initialValues={{}}
validationSchema={() => Yup.object().shape({`enter your validation keys here`})}
onSubmit={(values) => {
console.log('values after submit', values);
}}
>
{(formikProps) => {
const { values, handleChange } = formikProps;
return (
<Form>
<label>
name
<input name="name" onChange={handleChange} />
</label>
<label>
age
<input name="age" type="number" onChange={handleChange} />
</label>
<button
type="button"
onClick={() => {
console.log('show filled fields', values);
}}
>
Show Filled Fields
</button>
<button type={'submit'}> Submit</button>
</Form>
);
}}
</Formik>
Related
I have a form in my react application which is inside a modal pop up. so when the user closes the pop up i want to check if there is any changes made in the form fields.If so i will show a confirmation modal and if no changes i will close the pop up.
<FormProvider {...methods}>
<form onSubmit={handleSubmit(submitDetails)}>
<FormInput
onChange={handleChange(onChange, value)}
onBlur={onBlur}
value={value ?? ""}
name="name"
/>
<FormInput
onChange={handleChange(onChange, value)}
onBlur={onBlur}
value={value ?? ""}
name="age"
/>
<section className="submit-section">
<Button onClick={() => checkUnsavedAndClose()}>Cancel</Button>
<Button type="submit" disabled={!isValid}>
Save
</Button>
</section>
</form>
</FormProvider>
const checkUnsavedAndClose = () => {
// if the form is not updated
closePopUp();
// if the form is updated
alertPopup();
}
What is the best approach to validate the entire form irrespective of number of fields in it. i was thinking of checking whether the form is touched or dirty. but i am not sure that it would be the best solution. any inputs will be highly appreciated
Assuming the "handleChange" function is used for all inputs one thing you could do is use it to hold on state a variable for changes
handleChange(onChange, value) {
value !== originalValue && setState({anyChanges: true}) //or useState and set the state inside the modal
onChange(value)
}
you could also hold which fields were modified and not save to improve the pop-up message
by creating a boolean changed state. that you can change true/false. And you check the value when you try to close the popup.
const [changed, setChanged] = useState(false);
const handleChange() {
// your code
setChanged(true)
}
const checkUnsavedAndClose = () => {
if(changed) {
alertPopup();
} else {
closePopUp();
setChanged(false)
}
For normal html elements you can get the value of that element through a form.
function handleSubmit(event) {
event.preventDefault()
const formData = new FormData(e.target)
console.log(formData.get("test"))
// logs the value of the html element with the name "test"
}
<form onSubmit={handleSubmit}>
<input name="test" />
<button type="submit">Submit</button>
</form>
The form will assign a key "test" the value of whatever is inside the input on the form's submission.
My question: Is there a way to get this functionality to work with a Semantic UI Dropdown?
Below is ideally what I would think would work but I know doesn't because the component is a wrapper for other elements.
function handleSubmit(event) {
event.preventDefault()
const formData = new FormData(e.target)
console.log(formData.get("test"))
// logs the value of the html element with the name "test"
}
<form onSubmit={handleSubmit}>
<Dropdown name="test" selection options={
[{key: '1', text: 'text', value: '1'}]
}/>
<button type="submit">Submit</button>
</form>
On form submit, whatever value is selected in that dropdown is put into a key called "test" in formData. If no value is selected, an undefined value is given to the key "test."
Is this possible? I have another work around using a basic html selector but would like to not change a lot of already written code.
Yes, but you will need to deconstruct the dropdown component.
const [open, setOpen] = useState(false)
<Dropdown
trigger={<Button onClick={() => setOpen(true)}>Open</Button>}
onClose={() => setOpen(false)}
icon={null}
open={open}
simple
>
<Dropdown.Menu>
... add the options with the "name" tag ...
</Dropdown.Menu>
</Dropdown>
I am preparing a demo of add function where user enter two values in input field and result will be display on third field
But I am not able to show that result
Here is my code
https://codesandbox.io/s/flamboyant-smoke-ewkbd
return (
<div className="App">
Add Demo
<br />
<br />
<br />
{state.map(({ type, label, name }) => {
if (type === "text") {
return (
<div>
<label>{label}</label>
<input type="text" onChange={handleChange} name={name} />
</div>
);
}
})}
</div>
);
When I entered 2 in first field and 2 in second field .Expected output will be 4 in result field
I agree with your idea of using State, but better use form value where you can freely update your values.
If you need calculation, you can use number type rather than text
Use setForm for update value
Provide value with form values and show result with combination of first and second.
https://codesandbox.io/s/nice-violet-tv0vw
I'm having an input validation problem thats allowing the form to submit without having any selectorValues added. The check I have seems to only check for input inside the textarea but doesn't account for the Add button being pressed.
Here's a sandbox reproducing the issue.
I'm using Semantic-ui-react so my <Form.Field /> looks like this:
<Form.Field required>
<label>Selector Values:</label>
<TextArea
type="text"
placeholder="Enter selector values 1-by-1 or as a comma seperated list."
value={this.state.selectorValue}
onChange={this.handleSelectorValueChange}
required={!this.state.selectorValues.length}
/>
<Button positive fluid onClick={this.addSelectorValue}>
Add
</Button>
<ul>
{this.state.selectorValues.map((value, index) => {
return (
<Card>
<Card.Content>
{value}
<Button
size="mini"
compact
floated="right"
basic
color="red"
onClick={this.removeSelectorValue.bind(this, index)}
>
X
</Button>
</Card.Content>
</Card>
);
})}
</ul>
</Form.Field>
So in the above, <TextArea> has a required prop: !this.state.selectorValues.length. This is only checking for input inside the textarea, it should check that the value has been added by pressing the Add button before allowing the form to submit.
In your addSelectorValue add a check to see if this.state.selectorValue it not empty, if it is just return, this will prevent adding empty values to selectorValues
addSelectorValue = e => {
e.stopPropagation();
e.preventDefault();
if (!this.state.selectorValue) return;
//continue if this.state.selectorValue has a value
};
Before submitting add a check to see if this.selectorValues is empty, if so focus on textarea.
To focus we need to first create a ref to our textarea.
Create a ref to be
attached to a dom element
textareaRef = React.createRef();
// will use our ref to focus the element
focusTextarea = () => {
this.textareaRef.current.focus();
}
handleSubmit = () => {
const { selectorValues } = this.state;
if (!selectorValues.length) {
// call our focusTextarea function when selectorValues is empty
this.focusTextarea();
return;
}
this.setState({ submittedSelectorValues: selectorValues });
};
// attach our ref to Textarea
<Textarea ref={this.textareaRef} />
After some search ... required prop is for decorational purposes only - adding astrisk to field label.
It has nothing to form validation. You need a separate solution for that - try formik or set some condition within submit handler.
Formik plays nicely with yup validation schema - suitable for more complex, dynamic requirements.
I'm integrating Stripe Elements in my React project, using this simple component:
render () {
return (
<form onSubmit={event => this.onSubmit(event)}>
<label>
<CardElement className='Input' />
</label>
</form>
)
}
Problem is that I already have another form above where the user enters its billing info (address, zip code, country...). is it possible to pre-fill this field with the Zip code already entered before?
I've looked into Elements source code and see no value option possible. Is it possible somehow to use ref option to do so?
Thanks
According to this: https://stripe.com/docs/stripe-js/reference#elements-create (in options), you can pass the option value, I see here: https://github.com/stripe/react-stripe-elements/blob/master/src/components/Element.js#L26 that any viable option is allowed:
render () {
return (
<form onSubmit={event => this.onSubmit(event)}>
<label>
<CardElement
className='Input'
value={ { postalCode: this.state.postcode } }
/>
</label>
</form>
)
}