Set the value of a form based on state in React - javascript

Using Formik for validating some fields, if a state value is true I want that the value of a fields to be copied to the value of another one.
For example, value of mainAddress to be copied to address.
There is a state variable, setAddress which is set on false but it can be changed to true when a checkbox is clicked.
When this variable is set on true I want that the value of mainAddress to be copied to address
This is the code that works fine without copying that value:
import React from 'react';
import { Formik, Form, Field } from 'formik';
import { Input, Button, Label, Grid } from 'semantic-ui-react';
import * as Yup from 'yup';
import { Creators } from '../../../actions';
import './CreateCompanyForm.scss';
class CreateCompanyForm extends React.PureComponent {
constructor(props) {
super(props);
this.state = { // state variables
address: '',
mainAddress: '',
setAddress: false,
};
}
handleSubmit = values => {
// create company
};
toggleAddress = () => { // it toggles the value of setAddress
this.setState(prevState => ({
setAddress: !prevState.setAddress,
}));
};
render() {
const initialValues = { // the address and mainAddress are set to '' at the start
address: '',
mainAddress: '',
};
const validationSchema = Yup.object({
address: Yup.string().required('error'),
mainAddress: Yup.string().required('error'),
});
return (
<>
<Button type="submit" form="amazing"> // button for submit
Create company
</Button>
<Formik
htmlFor="amazing"
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={values => this.handleSubmit(values)}>
{({ values, errors, touched, setValues, setFieldValue }) => (
<Form id="amazing">
<Grid>
<Grid.Column> // mainAddress value
<Label>Main Address</Label>
<Field name="mainAddress" as={Input} />
</Grid.Column>
<Grid.Column> // address value
<Label>Address</Label>
<Field name="address" as={Input} />
<div>
{this.state.setAddress // here is how I've tried to set that value
? values.address.setFieldValue(values.mainAddress)
: console.log('nope')}
{touched.address && errors.address ? errors.address : null}
</div>
</Grid.Column>
</Grid>
<Checkbox
label="Use same address"
onClick={() => this.toggleAddress()}
/>
</Form>
)}
</Formik>
</>
);
}
}
So I've tried more ways to solve it but without success. Now in the code it is:
{this.state.setAddress
? values.address.setFieldValue(values.mainAddress)
: console.log('nope')}
Other one was: (this.state.setAddress ? values.address = values.mainAddress)
None of them work. Is it possible to get the value from values.mainAddress and copy it to values.address? Or to its input?

You can rewrite the Field component for address accordingly.
<Field name="address">
{({
field, // { name, value, onChange, onBlur }
}) => {
values.address = values.mainAddress;
return (
<div>
<input
{...field}
type="text"
placeholder="Address"
/>
</div>
);
}}
</Field>
Here we are setting the value of address field to values.mainAddress if setAdress checkbox is checked else we let formik value to fill it.
Here is the working codesandbox code - https://codesandbox.io/s/fervent-tereshkova-sro93?file=/index.js

Formik also provides values object you could use that for updating address value same as mainAddress. Just provide name attribute to both input fields then assign like this - props.values.address = {...props.values.mainAddress}

Related

Material UI + React Form Hook + multiple checkboxes + default selected

I am trying to build a form that accommodates multiple 'grouped' checkboxes using react-form-hook Material UI.
The checkboxes are created async from an HTTP Request.
I want to provide an array of the objects IDs as the default values:
defaultValues: { boat_ids: trip?.boats.map(boat => boat.id.toString()) || [] }
Also, when I select or deselect a checkbox, I want to add/remove the ID of the object to the values of react-hook-form.
ie. (boat_ids: [25, 29, 4])
How can I achieve that?
Here is a sample that I am trying to reproduce the issue.
Bonus point, validation of minimum selected checkboxes using Yup
boat_ids: Yup.array() .min(2, "")
I've been struggling with this as well, here is what worked for me.
Updated solution for react-hook-form v6, it can also be done without useState(sandbox link below):
import React, { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
export default function CheckboxesGroup() {
const defaultNames = ["bill", "Manos"];
const { control, handleSubmit } = useForm({
defaultValues: { names: defaultNames }
});
const [checkedValues, setCheckedValues] = useState(defaultNames);
function handleSelect(checkedName) {
const newNames = checkedValues?.includes(checkedName)
? checkedValues?.filter(name => name !== checkedName)
: [...(checkedValues ?? []), checkedName];
setCheckedValues(newNames);
return newNames;
}
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
{["bill", "luo", "Manos", "user120242"].map(name => (
<FormControlLabel
control={
<Controller
name="names"
render={({ onChange: onCheckChange }) => {
return (
<Checkbox
checked={checkedValues.includes(name)}
onChange={() => onCheckChange(handleSelect(name))}
/>
);
}}
control={control}
/>
}
key={name}
label={name}
/>
))}
<button>Submit</button>
</form>
);
}
Codesandbox link: https://codesandbox.io/s/material-demo-54nvi?file=/demo.js
Another solution with default selected items done without useState:
https://codesandbox.io/s/material-demo-bzj4i?file=/demo.js
Breaking API changes made in 6.X:
validation option has been changed to use a resolver function wrapper and a different configuration property name
Note: Docs were just fixed for validationResolver->resolver, and code examples for validation in repo haven't been updated yet (still uses validationSchema for tests). It feels as if they aren't sure what they want to do with the code there, and it is in a state of limbo. I would avoid their Controller entirely until it settles down, or use Controller as a thin wrapper for your own form Controller HOC, which appears to be the direction they want to go in.
see official sandbox demo and the unexpected behavior of "false" value as a string of the Checkbox for reference
import { yupResolver } from "#hookform/resolvers";
const { register, handleSubmit, control, getValues, setValue } = useForm({
resolver: yupResolver(schema),
defaultValues: Object.fromEntries(
boats.map((boat, i) => [
`boat_ids[${i}]`,
preselectedBoats.some(p => p.id === boats[i].id)
])
)
});
Controller no longer handles Checkbox natively (type="checkbox"), or to better put it, handles values incorrectly. It does not detect boolean values for checkboxes, and tries to cast it to a string value. You have a few choices:
Don't use Controller. Use uncontrolled inputs
Use the new render prop to use a custom render function for your Checkbox and add a setValue hook
Use Controller like a form controller HOC and control all the inputs manually
Examples avoiding the use of Controller:
https://codesandbox.io/s/optimistic-paper-h39lq
https://codesandbox.io/s/silent-mountain-wdiov
Same as first original example but using yupResolver wrapper
Description for 5.X:
Here is a simplified example that doesn't require Controller. Uncontrolled is the recommendation in the docs. It is still recommended that you give each input its own name and transform/filter on the data to remove unchecked values, such as with yup and validatorSchema in the latter example, but for the purpose of your example, using the same name causes the values to be added to an array that fits your requirements.
https://codesandbox.io/s/practical-dijkstra-f1yox
Anyways, the problem is that your defaultValues doesn't match the structure of your checkboxes. It should be {[name]: boolean}, where names as generated is the literal string boat_ids[${boat.id}], until it passes through the uncontrolled form inputs which bunch up the values into one array. eg: form_input1[0] form_input1[1] emits form_input1 == [value1, value2]
https://codesandbox.io/s/determined-paper-qb0lf
Builds defaultValues: { "boat_ids[0]": false, "boat_ids[1]": true ... }
Controller expects boolean values for toggling checkbox values and as the default values it will feed to the checkboxes.
const { register, handleSubmit, control, getValues, setValue } = useForm({
validationSchema: schema,
defaultValues: Object.fromEntries(
preselectedBoats.map(boat => [`boat_ids[${boat.id}]`, true])
)
});
Schema used for the validationSchema, that verifies there are at least 2 chosen as well as transforms the data to the desired schema before sending it to onSubmit. It filters out false values, so you get an array of string ids:
const schema = Yup.object().shape({
boat_ids: Yup.array()
.transform(function(o, obj) {
return Object.keys(obj).filter(k => obj[k]);
})
.min(2, "")
});
Here is a working version:
import React from "react";
import { useForm, Controller } from "react-hook-form";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
export default function CheckboxesGroup() {
const { control, handleSubmit } = useForm({
defaultValues: {
bill: "bill",
luo: ""
}
});
return (
<form onSubmit={handleSubmit(e => console.log(e))}>
{["bill", "luo"].map(name => (
<Controller
key={name}
name={name}
as={
<FormControlLabel
control={<Checkbox value={name} />}
label={name}
/>
}
valueName="checked"
type="checkbox"
onChange={([e]) => {
return e.target.checked ? e.target.value : "";
}}
control={control}
/>
))}
<button>Submit</button>
</form>
);
}
codesandbox link: https://codesandbox.io/s/material-demo-65rjy?file=/demo.js:0-932
However, I do not recommend doing so, because Checkbox in material UI probably should return checked (boolean) instead of (value).
Here's my solution, which is not using all the default components from Material UI cause at my interface each radio will have an icon and text, besides the default bullet point not be showed:
const COMPANY = "company";
const INDIVIDUAL = "individual";
const [scope, setScope] = useState(context.scope || COMPANY);
const handleChange = (event) => {
event.preventDefault();
setScope(event.target.value);
};
<Controller
as={
<FormControl component="fieldset">
<RadioGroup
aria-label="scope"
name="scope"
value={scope}
onChange={handleChange}
>
<FormLabel>
{/* Icon from MUI */}
<Business />
<Radio value={COMPANY} />
<Typography variant="body1">Company</Typography>
</FormLabel>
<FormLabel>
{/* Icon from MUI */}
<Personal />
<Radio value={INDIVIDUAL} />
<Typography variant="body1">Individual</Typography>
</FormLabel>
</RadioGroup>
</FormControl>
}
name="scope"
control={methods.control}
/>;
Observation: At this example I use React Hook Form without destruct:
const methods = useForm({...})
This is my solution with react hook form 7, the other solutions don't work with reset or setValue.
<Controller
name={"test"}
control={control}
render={({ field }) => (
<FormControl>
<FormLabel id={"test"}>{"label"}</FormLabel>
<FormGroup>
{items.map((item, index) => {
const value = Object.values(item);
return (
<FormControlLabel
key={index}
control={
<Checkbox
checked={field.value.includes(value[0])}
onChange={() =>
field.onChange(handleSelect(value[0],field.value))
}
size="small"
/>
}
label={value[1]}
/>
);
})}
</FormGroup>
</FormControl>
)}
/>
link to codesandbox: Mui multiple checkbox

Unable to clear controlled input with setstate

currently trying to use setState to clear a controlled input,
adding a value to the input field and using setState to clear it
The function that clears the state
createNewBoard = (e) => {
e.preventDefault();
const newItem = { boardname: this.state.currentValue, todo: []};
const updatedList = [...this.state.boards, newItem]
this.setState({
boards: updatedList,
currentValue: ''
});
}
passing down the props to the component
render() {
return(
<>
{ this.state.isBoardOpen ?
<ActiveCreateBoard
toggleCreateBoard={this.toggleCreateBoard}
onChange={this.onChange}
currentValue={this.currentValue}
createNewBoard={this.createNewBoard}
/> : <CreateBoard toggleCreateBoard={this.toggleCreateBoard}/> }
<ShowAllBoards boards={this.state.boards}/>
</>
)
}
the component itself which is not updating the input field
const ActiveCreateBoard = ({ toggleCreateBoard, onChange, currentValue, createNewBoard }) => {
return(
<div className="card">
<div className="card-body">
<form onSubmit={createNewBoard}>
<h4>Pick a board name</h4>
<input
type="text"
onChange={onChange}
value={currentValue}/>
</form>
</div>
<button onClick={toggleCreateBoard}>close</button>
</div>
)
}
this.setState is clearing the currentValue in state, but the value of the input field is not reflecting the update in state
Your input field is not updating because you are passing down this.currentValue, which will be undefined:
<ActiveCreateBoard
toggleCreateBoard={this.toggleCreateBoard}
onChange={this.onChange}
currentValue={this.currentValue}
createNewBoard={this.createNewBoard}
/>
Instead, you need to pass down the value from state.
Change to use this.state.currentValue:
<ActiveCreateBoard
toggleCreateBoard={this.toggleCreateBoard}
onChange={this.onChange}
currentValue={this.state.currentValue} // <---
createNewBoard={this.createNewBoard}
/>

Redux Form: Input stays with 'touched: false'

Wanted to validate my inputs and change the CSS depending of the user interaction.
Starting with a required validation method I wrap all my inputs component with a <Field> and pass to validate an array of func. Just required for now.
But for all my fields the value stay the same touched: false and error: "Required". If I touch or add stuff in the input, those values stay the same.
Validation
export const required = value => (value ? undefined : 'Required')
NameInput
import React from 'react';
import { Field } from 'redux-form'
import InputItem from 'Components/InputsUtils/InputItem';
import { required } from 'Components/InputsUtils/Validation';
const NameInput = () => (
<Field
name={item.spec.inputName}
type={item.spec.type}
component={InputItem}
validate={[required]}
props={item}
/>
);
export default NameInput;
InputItem
import React from 'react';
const InputItem = ({ spec, meta: { touched, error } }) => {
const { type, placeholder } = spec;
return (
<input
className="input"
type={type}
placeholder={placeholder}
/>
);
};
export default InputItem;
There are 2 solutions to solve the "touched is always false" issue.
1) Ensure that input.onBlur is called in your component
For an input:
const { input } = this.props
<input {...input} />
For custom form elements without native onBlur:
const { input: { value, onChange, onBlur } } = this.props
const className = 'checkbox' + (value ? ' checked' : '')
<div
className={className}
onClick={() => {
onChange(!value)
onBlur()
}}
/>
2) Declare your form with touchOnChange
const ReduxFormContainer = reduxForm({
form: 'myForm',
touchOnChange: true,
})(MyForm)
The redux-form controls its own props within your <input /> element as long as you use the spread operator to pass those props into your input.
For example, where you are doing const InputItem = ({ spec, meta: { touched, error } }) => ...
Try destructing the input from the Component: const InputItem = ({ input, spec, meta: { touched, error } }) => ...
And where you have your <input ... />, try doing the following:
<input
{...input}
className="input"
type={type}
placeholder={placeholder}
/>
The redux-form captures any onBlur and onChange events and uses its own methods to change the touched state. You just need to pass those along as shown above.
These are what you need: https://redux-form.com/7.1.2/docs/api/field.md/#input-props
Another point to consider:
I passed {...props} to my custom component, however, touched still remained false.
That is because although props contained the input object, my component couldn't
deduce onBlur from it. When explicitly stating <CustomComponent {...this.props} onBlur={this.props.input.onBlur}, it worked as expected.

Reusable form fields in React

If i have the following dialog/modal:
<Modal
open={this.state.createAccountModalOpen}
trigger={<Link size="m" theme="bare" href="#" className="main-menu-item" onClick={this.handleOpenModalCreateAccount}>Create account</Link>}
closeIcon
onClose={() => { this.setState({
createAccountModalOpen: false,
}); }}
>
<Header icon='add user' content='Create account' />
<Modal.Content>
<Form />
</Modal.Content>
<Modal.Actions>
<Button color='green' onClick={this.handleSubmit}>
<Icon name='add user' /> Create account
</Button>
</Modal.Actions>
</Modal>
Basically this is a React Semantic-ui Modal/Dialog. Now What i want to do is make Form reusable (the Form component contains 4 input fields), so i can use it in other modals or components. What would be the best way so that when I click on Create account, it gathers the data from the form and then submits it?
Do I have to pass functions to the Form to try store the data in the main Modal component? or is there a better way to get the validated data from the form?
I’m on my phone so I’m limited.
You want to define your custom function in the parent component where you call your Modal. Then pass that function to it as a prop modal onComplete={this.submitEmail}
Then in your modal component call this.props.onComplete in your handleSubmit.
Then from here out you can define the custom function you want to use wiTh the model and pass it through with onComplete={whateverFunction}
In order to only show the inputs that you want you could set up a series of render if statements. Then when you call your Modal you can pass through renderIfText={“email”} and in your model if this.props.renderIfText=email render email input.
import React from 'react';
class ReusableModalForm extends React.Component {
constructor(props){
super(props);
this.state ={
};
}
handleChange(e) {
let {name, value} = e.target;
this.setState({
[name]: value,
usernameError: name === 'username' && !value ? 'username must have a value' : null,
emailError: name === 'email' && !value ? 'email must have a value' : null,
passwordError: name === 'password' && !value ? 'password must have a value' : null,
});
}
handleSubmit(e) {
e.preventDefault();
this.props.onComplete(this.state)
}
render() {
return (
<Modal
open={this.state.createAccountModalOpen}
trigger={<Link size="m" theme="bare" href="#" className="main-menu-item" onClick={this.handleSubmit}>{this.props.buttonText}</Link>}
closeIcon
onClose={() => { this.setState({
createAccountModalOpen: false,
}); }}
>
<Header icon='add user' content='Create account' />
<Modal.Content>
<Form />
</Modal.Content>
<Modal.Actions>
<Button color='green' onClick={this.handleSubmit}>
<Icon name='add user' /> {this.props.buttonText}
</Button>
</Modal.Actions>
</Modal>
);
}
}
export default ReusableModalForm;
In order to make your <Form /> reusable you need to determine what are the inputs/outputs to your Form and allow any potential parent component to access/manipulate it via props.
Perhaps something like:
<CreateAccountForm
input1DefaultValue={...}
input2DefaultValue={...}
onSubmit={yourCreateAccountFormHandler}
/>
Do I have to pass functions to the Form to try store the data in the main Modal component? or is there a better way to get the validated data from the form?
It depends on how you implement Form and your input fields.
I would recommend react-form library or, if you want to have your own implementation - using redux state and wire your inputs/form to redux.
If no redux then you will need to store the state of inputs in the modal.
Whenever you compose components, you share data between them using props. I will be passing "name and label" props to stateless functional component named;
input.js
import React from "react";
const Input = ({name,label}) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input
autoFocus
name={name}
id={name}
className="form-control"
aria-describedby="emailHelp"
/>
);
};
export default Input;
form.js
import React, { Component } from "react";
import Input from "./common/input";
class RegisterForm extends Form {
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input name="username" label="username" />
<input name="email" label="email" />
<input name="password" label="password" />
</form>
</div> ); } }

Could not type any text inside textfield

I am using redux-form-material-ui for my form. With below code, i cannot type anything on the textfield. I mean to say nothing gets type in the textfield. There are two textfield in my form and one Autocomplete. One is for device name and another for timeout value. Autocomplete works though. Why is it not showing the text i have typed?
What might be the reason for this issue? Have i done somewhere mistake?
Please see an image attached. I cant write anything in device name and timeout input box. Only autocomplete box can be selected and is shown on input box.
Here is my code
import React, { Component } from 'react';
import _ from 'lodash';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import {
AutoComplete as MUIAutoComplete, MenuItem,
FlatButton, RaisedButton,
} from 'material-ui';
import {
AutoComplete,
TextField
} from 'redux-form-material-ui';
const validate = values => {
const errors = {};
const requiredFields = ['deviceName', 'deviceIcon', 'deviceTimeout'];
requiredFields.forEach(field => {
if (!values[field]) {
errors[field] = 'Required';
}
});
return errors;
};
class DeviceName extends Component {
handleSubmit = (e) => {
e.preventDefault();
this.props.handleNext();
}
render() {
const {
handleSubmit,
fetchIcon,
stepIndex,
handlePrev,
pristine,
submitting
} = this.props;
return (
<div className="device-name-form">
<form>
<div>
<Field
name="deviceName"
component={TextField} {/* cannot type */}
floatingLabelStyle={{ color: '#1ab394' }}
hintText="Device Name"
onChange={(e) => this.setState({ deviceName: e.target.name })}
/>
</div>
<div>
<Field
name="deviceIcon"
component={AutoComplete} {/* works */}
hintText="icon"
openOnFocus
filter={MUIAutoComplete.fuzzyFilter}
className="autocomplete"
dataSource={listOfIcon}
onNewRequest={(e) => { this.setState({ deviceIcon: e.id }); }}
/>
</div>
<div>
<Field
name="deviceTimeout"
component={TextField} {/* cannot type */}
floatingLabelStyle={{ color: '#1ab394' }}
hintText="Device Timeout"
ref="deviceTimeout" withRef
onChange={(e) => this.setState({ deviceTimeout: e.target.name })}
/>
</div>
<div style={{ marginTop: 12 }}>
<RaisedButton
label={stepIndex === 4 ? 'Finish' : 'Next'}
primary
disabled={pristine || submitting}
className="our-btn"
onTouchTap={(e) => handleSubmit(e)}
/>
</div>
</form>
</div>
);
}
}
const mapStateToProps = ({ fetchIcon }) => ({
fetchIcon
});
const DeviceForm = reduxForm({
form: 'DeviceForm',
validate,
})(DeviceName);
export default connect(mapStateToProps)(DeviceForm);
By adding onChange to your Fields, aren't you preventing redux form from accepting the new values from that input field? Is there a reason you are attempting to add these to your Component state?
The examples in the documentation certainly suggest you should not need to do this - http://redux-form.com/6.1.1/examples/material-ui/
I guess you can simplify your form as-
class DeviceName extends Component {
handleSubmit = (values) => {
console.log(values); // Do something with values
}
render() {
const {
....
handleSubmit //***Change
} = this.props;
return (
<div className="device-name-form">
<form onSubmit={handleSubmit(this.handleSubmit)}>
<div>
<Field
name="deviceName"
component={TextField} {/* cannot type */}
floatingLabelStyle={{ color: '#1ab394' }}
hintText="Device Name"
//*** line removed
/>
</div>
.....
.....
<div style={{ marginTop: 12 }}>
<RaisedButton
type="submit" // setting type
label={stepIndex === 4 ? 'Finish' : 'Next'}
primary
disabled={pristine || submitting}
className="our-btn"
/>
</div>
</form>
</div>
);
}
}
I would guess that the problem is in your onChange handlers - you probably need to use target.value rather than target.name:
onChange={(e) => this.setState({ deviceTimeout: e.target.value})
I had the same issue, turned out I used the wrong import. I was using the normal import:
import { Field, reduxForm } from 'redux-form'
Because my store is immutable (using Immutable.js) I had to use the immutable import:
import { Field, reduxForm } from 'redux-form/immutable'
Some kind of error logging for redux-form would have been handy in this case.

Categories

Resources