Creating a Dynamic on Demand Input field - reactjs

I am new to React and doing a personal project to help with some organization in my life.
I have a field where I need to be able to add multiple names some times. I think I am close...I can't get the fields to appear but they act like they are all the same field, like they are bound together
Here is what I am getting
NameInput.jsx (component)
import React, { useState } from "react";
import { Form, Label } from "semantic-ui-react";
const NameInput = ({
input,
width,
type,
placeholder,
meta: { touched, error }
}) => {
let [inputs, setInputs] = useState([""]);
return (
<div className="nameField">
<Form.Field error={touched && !!error} width={width}>
{inputs.map((value, i) => (
<div>
<label>Name {i + 1}</label>
<input {...input} placeholder={placeholder} type={type} />{" "}
{touched && error && (
<Label basic color="red">
{error}
</Label>
)}
{e =>
setInputs(
inputs.map((value, j) => {
if (i === j) value = e.target.value;
return value;
})
)
}
</div>
))}
</Form.Field>
<button
className="ui compact button"
onClick={() => setInputs(inputs.concat(""))}
>
Add Additional Seller
</button>
</div>
);
};
export default NameInput;
And this is how I call the component. This stores to my firebase as nameField
<label>Name Field</label>
<Field
name="nameField"
type="text"
component={NameInput}
placeholder="Enter Full Name"
/>
Ideally, I'd want it to save has nameField, namefield2, nameField3 but I believe I can get that part solved on my own if I could just get my component to play nice.

Haven't you ever get a warning that a key should be provided for list items?
You should assign a unique key for each input div.

Related

How to add react-phone-number-input to -react-final-form?

I'm currently creating a form using react-final-form and trying to use react-phone-number-input with it through integration as an adapter, as displayed through this example.
I attempted to use the example to learn how it is done, but I'm not sure how to access the component and create the adapter for it properly.
import React from 'react';
import { Form, Field } from 'react-final-form';
import PhoneInput from 'react-phone-number-input';
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const onSubmit = async values => {
await sleep(300)
window.alert(JSON.stringify(values, 0, 2))
}
const PhoneAdapter = ({ input, meta, ...rest }) => (
<PhoneInput
{...input}
{...rest}
value={input.value}
onChange={(event, value) => input.onChange(value)}
/>
)
class ContactForm extends React.Component {
render() {
return (
<>
<Form
onSubmit={onSubmit}
initialValues={{ }}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}>
<fieldset>
<Field component={PhoneAdapter} />
</fieldset>
<fieldset>
<button type="submit" disabled={submitting || pristine}>
Submit
</button>
</fieldset>
<pre>{JSON.stringify(values, 0, 2)}</pre>
</form>
)}
/>
</>
);
}
}
export default ContactForm;
Update: July 2019
Apparently, all you need to do is to spread the input property of Field. Works flawlessly. Learn about spreading if you're not familiar with it.
const PhoneAdapter = ({ input }) => (
<PhoneInput {...input} />
)
<Field name="phone" placeholder="Enter phone number" component={PhoneAdapter} />
I ended up experimenting with the FieldRenderProps props until it worked out. I wasn't so sure whether it would work or not, as react-phone-number-input is two elements in a component. I thought it would implement the input on only one of the elements.
By using input, I gain access to the input's props. Hence, I called upon it's value, as the default looks like so:
<PhoneInput
placeholder="Enter phone number"
value={ this.state.value } // This is what I called.
onChange={ value => this.setState({ value }) }/>
I then did the same for the onChange function prop.
const PhoneAdapter = ({ input }) => (
<PhoneInput value={input.value.value} onChange={value => input.onChange(value)} />
)
Finally, I used the component adapter like so:
<Field name="phone" placeholder="Enter phone number" component={PhoneAdapter} />

Redux Forms sometimes ends up with register/unregister infinite loop

I'm having trouble taming Redux Forms.
I have the following form and fields. Which seems to work if I simply add the correct data and submit, but if I try to cause validation errors and re-enter data a few times it sometimes ends up in an infinite loop.
The infinite loop is calling action ##redux-form/REGISTER_FIELD and action ##redux-form/UNREGISTER_FIELD repeatedly and eventually results in the following error.
Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Can anyone help me to understand what might be causing this and what steps I can take to get it working please?
ContactPage.js
import React, {Component} from 'react';
import ContactForm from './contact-form';
class ContactPage extends Component {
submit = values => {
console.log(values);
};
render() {
return (
<div>
<ContactForm onSubmit={this.submit}/>
</div>
);
}
}
export default ContactPage;
ContactForm.js
import React from 'react';
import {Field, reduxForm} from 'redux-form';
import {isEmail, isRequired, maxLength} from '../validation';
import {Input, Select, TextArea} from './form-elements';
let ContactForm = ({handleSubmit}) =>
<form onSubmit={handleSubmit}>
<div>
<Field name="fullname"
label="Full Name"
component={Input}
type="text"
validate={[isRequired, maxLength(5)]}
/>
</div>
<div>
<Field name="email" component={Input} type="email"
validate={[isRequired, maxLength(254), isEmail]}
classes={['email-field']}
/>
</div>
<div>
<Field name="message" component={TextArea}
validate={[isRequired]}
/>
</div>
<button type="submit">Submit</button>
</form>
;
ContactForm = reduxForm({
form: 'contact'
})(ContactForm);
export default ContactForm;
FormElements.js
import React from 'react';
const Label = ({label, forName}) => <label htmlFor={forName} className="form-label">{label}</label>;
export const Input = ({input, label, type, classes = [], meta: {touched, error}}) => (
<div className={['form-field', 'input', ...classes].join(' ')}>
<Label label={label} forName={input.name}/>
<div>
<input {...input} type={type} placeholder={label}
className={['form-input', touched && error ? 'form-error' : ''].join(' ')}/>
{touched && error && <p className='form-error'>{error}</p>}
</div>
</div>
);
export const TextArea = ({input, label, classes = [], meta: {touched, error}}) => (
<div className={['form-field', 'text-area', ...classes].join(' ')}>
<Label label={label} forName={input.name}/>
<div>
<textarea {...input} placeholder={label} className={[touched && error ? 'form-error' : ''].join(' ')}/>
{touched && error && <p className='form-error'>{error}</p>}
</div>
</div>
);
Don't do this:
validate={[isRequired, maxLength(5)]}
every time the form is rendered maxLength(5) will construct a new function, which will cause field to rerender (because this.props.validate !== nextProps.validate)
You can use specifically defined instances of parameterized validation rules:
const maxLength = max => value =>
value && value.length > max ? `Must be ${max} characters or less` : undefined;
const maxLength15 = maxLength(15);
<Field
name="username"
type="text"
component={renderField}
label="Username"
validate={[required, maxLength15]}
/>
I had the same issue. validate={[isRequired, maxLength(5)]} didn't help. Figured out that in my component was
useEffect(() => {
dispatch(reset('myForm'));
}, [])
Helped
useEffect(() => {
return dispatch(reset('myForm'));
}, [])

Programatically changing a FieldArray value in Redux-Form

I'm trying to figure out how to use this.props.dispatch(change) in order use one field selector value to update another fields value within a FieldArray.
https://codesandbox.io/s/2p7k7jn930
I can't seem to get the syntax in this correct.
this.props.dispatch(
change("FieldArraysForm", `${props.member}.firstName`, this.props.hasLastName)
);
Any thoughts? Expected behavior would be to add a member and then have anything typed into the Last Name field be programmatically updated in the First Name field.
/**
The following can replace the file in the Field Arrays example
(https://github.com/erikras/redux-form/tree/master/examples/fieldArrays) to demonstrate this functionality.
**/
import React from "react";
import { connect } from "react-redux";
import {
Field,
FieldArray,
reduxForm,
formValueSelector,
change
} from "redux-form";
import validate from "./validate";
const selector = formValueSelector("fieldArrays");
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} type={type} placeholder={label} />
{touched && error && <span>{error}</span>}
</div>
</div>
);
class Member extends React.Component {
componentDidUpdate(prevProps, props) {
if (this.props.hasLastName !== prevProps.hasLastName) {
this.props.dispatch(
change("FieldArraysForm", `${props.member}.firstName`, this.props.hasLastName)
);
}
}
render() {
const { member, index, fields, hasLastName } = this.props;
return (
<li key={index}>
<button
type="button"
title="Remove Member"
onClick={() => fields.remove(index)}
/>
<h4>Member #{index + 1}</h4>
<Field
name={`${member}.firstName`}
type="text"
component={renderField}
label="First Name"
/>
<Field
name={`${member}.lastName`}
type="text"
component={renderField}
label="Last Name"
/>
{hasLastName && <p>{hasLastName}</p>}
</li>
);
}
}
Member = connect((state, props) => ({
hasLastName: selector(state, `${props.member}.lastName`)
}))(Member);
const renderMembers = ({ fields, meta: { touched, error } }) => (
<ul>
<li>
<button type="button" onClick={() => fields.push({})}>
Add Member
</button>
{touched && error && <span>{error}</span>}
</li>
{fields.map((member, index) => (
<Member member={member} fields={fields} index={index} key={index} />
))}
</ul>
);
const FieldArraysForm = props => {
const { handleSubmit, pristine, reset, submitting } = props;
return (
<form onSubmit={handleSubmit}>
<Field
name="clubName"
type="text"
component={renderField}
label="Club Name"
/>
<FieldArray name="members" component={renderMembers} />
<div>
<button type="submit" disabled={submitting}>
Submit
</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
);
};
export default reduxForm({
form: "fieldArrays", // a unique identifier for this form
validate
})(FieldArraysForm);
In order to access the FieldArray dynamically, you would want to change this:
change("FieldArraysForm", `${props.member}.firstName`, this.props.hasLastName)
to this:
change("FieldArraysForm", `members[${this.props.index}].firstName`, this.props.hasLastName)
Also, pass in the form selector specified:
const selector = formValueSelector("fieldArrays");
This would give you:
change("fieldArrays", `members[${this.props.index}].firstName`, this.props.hasLastName)
Had to get some help on this one - thanks goes to #Amanda Field.
You need to specify the index of the field in FieldArray you want to change. To do so, just use <fieldName>.<index>.<propertyName>, for instance:
this.props.change('members.0.firstName', 'Donald')
where member is the name of your FieldArray field, 0 is the index of the item in the array you want to change and firstName is the property of the object.
See sandbox here

Control the Redux-form with the button

I am using the Redux-form to do a task.
This form in a form container.
In the form container or in the form component.
There are two buttons. An add button and a subtract button.
The form component is:
import React from 'react'
import { Field, reduxForm } from 'redux-form'
import TextField from 'material-ui/TextField'
import RaisedButton from 'material-ui/RaisedButton'
const renderTextField = ({ input, label, meta: { touched, error }, ...custom }) => (
<TextField hintText={label}
floatingLabelText={label}
errorText={touched && error}
{...input}
{...custom}
/>
)
const ActivityDetailForm = props => {
const { handleSubmit, pristine, reset, submitting,} = props
return (
<form onSubmit={handleSubmit}>
<div>
<RaisedButton
type="submit"
disabled={pristine || submitting}
label="saveChange"
fullWidth={true}
secondary={true}
/>
</div>
</form>
)
}
export default reduxForm({
form: 'ActivityDetailForm', // a unique identifier for this form
})(ActivityDetailForm)
Now, I face a problem. When I click the add button,
<div>
<Field name="field1" component={renderTextField} label="text1: "/>
</div>
the code above will be created in the form element.
When I click the add button again, the div element which includes the Field named field2 will be created in the form element.
... Field named field3
... Field named field4
... Field named field5
...
When I click the subtract button. The last Field element will be destroyed.
Do you know the method to solve this problem?
The following (untested) is a pretty basic example on how to achieve dynamic inputs with a FieldArray. You'd have to tweak this a bit to tailor it to your specific scenario.
const renderTextField = ({ input, label, meta: { touched, error }, ...custom }) => (
<TextField hintText={label}
floatingLabelText={label}
errorText={touched && error}
{...input}
{...custom}
/>
)
const ActivityDetailForm = props => {
const { handleSubmit, pristine, reset, submitting,} = props
const renderFieldArray = ({ fields }) => (
<div>
<div>
<RaisedButton
onTouchTap={() => fields.push({})}
label="Add"
/>
</div>
{fields.map((field, index) => (
<div>
<div key={index}>
<Field
name={`${field}.name`}
label={`Text ${index + 1}`}
component={renderTextField}
/>
</div>
<div>
<RaisedButton
onTouchTap={() => fields.remove(index)}
label="Remove"
/>
</div>
</div>
))}
</div>
);
return (
<form onSubmit={handleSubmit}>
<div>
<FieldArray
name="textFields"
component={renderFieldArray}
/>
<RaisedButton
type="submit"
disabled={pristine || submitting}
label="saveChange"
fullWidth={true}
secondary={true}
/>
</div>
</form>
)
}
export default reduxForm({
form: 'ActivityDetailForm', // a unique identifier for this form
})(ActivityDetailForm)

unable to set defaultValue in redux-form-material-ui TextField

I'm unable to set a default value for the textField component.
I tried using default value, but as long as I'm using the redux-form-material-ui it just doesn't work.
I really don't understand what am I doing wrong (seems pretty basic)...
exmaple (just changed their fieldArray example a little):
import React from 'react'
import { Field, FieldArray, reduxForm } from 'redux-form'
import validate from './validate'
import {TextField} from 'redux-form-material-ui'
const renderField = (props) => {
console.log(props);
const { input, label, type, meta: { touched, error } } = props;
console.log(input);
return <div>
<label>{label}</label>
<div>
// Will not show "someValue", it will just be blank
<TextField defaultValue="someValue" {...input} type={type} placeholder={label}/>
{touched && error && <span>{error}</span>}
</div>
</div>
}
const renderMembers = ({ fields, meta: { touched, error, submitFailed } }) => (
<ul>
<li>
<button type="button" onClick={() => fields.push({})}>Add Member</button>
{(touched || submitFailed) && error && <span>{error}</span>}
</li>
{fields.map((member, index) =>
<li key={index}>
<button
type="button"
title="Remove Member"
onClick={() => fields.remove(index)}/>
<h4>Member #{index + 1}</h4>
<Field
name={`${member}.firstName`}
type="text"
component={renderField}
label="First Name"/>
<Field
name={`${member}.lastName`}
type="text"
component={renderField}
label="Last Name"/>
<FieldArray name={`${member}.hobbies`} component={renderHobbies}/>
</li>
)}
</ul>
)
const renderHobbies = ({ fields, meta: { error } }) => (
<ul>
<li>
<button type="button" onClick={() => fields.push()}>Add Hobby</button>
</li>
{fields.map((hobby, index) =>
<li key={index}>
<button
type="button"
title="Remove Hobby"
onClick={() => fields.remove(index)}/>
<Field
name={hobby}
type="text"
component={renderField}
label={`Hobby #${index + 1}`}/>
</li>
)}
{error && <li className="error">{error}</li>}
</ul>
)
const FieldArraysForm = (props) => {
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit}>
<Field name="clubName" type="text" component={renderField} label="Club Name"/>
<FieldArray name="members" component={renderMembers}/>
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
export default reduxForm({
form: 'fieldArrays', // a unique identifier for this form
validate
})(FieldArraysForm)
Thanks.
I was having the same issue. Just read through the documentation again and saw this
No Default Values
Because of the strict "controlled component" nature of redux-form, some of the Material UI functionality related to defaulting of values has been disabled e.g. defaultValue, defaultDate, defaultTime, defaultToggled, defaultChecked, etc. If you need a field to be initialized to a certain state, you should use the initialValues API of redux-form.
It's probably only one way to make form of editing.
It cannot be restored from initial redux Form values.
Input
export default function ({ input, label, meta: { touched, error }, ...custom }) {
if ( input.value === '' && custom.cvalue ) { // hack for redux form with material components
input.onChange(String(custom.cvalue));
}
return (
<TextField
{...input}
{...custom}
fullWidth={true}
hintText={label}
floatingLabelText={label}
errorText={touched && error}
/>
)
}
Select
export default function ({ input, label, meta: { touched, error }, onChange, children, ...custom }) {
if ( input.value === '' && custom.cvalue ) { // hack for redux form with material components
if ( is.function(onChange) ) {
onChange(custom.cvalue);
}
input.onChange(custom.cvalue);
}
return (
<SelectField
{...input}
{...custom}
fullWidth={true}
children={children}
floatingLabelText={label}
errorText={touched && error}
onChange={(event, index, value) => {
if ( is.function(onChange) ) { // and custom onChange for f....g ....
value = onChange(value);
}
input.onChange(value);
}}/>
)
}
then in template
its can be way to make form of editing existing entity ....
<Field
name="study"
label="Studies"
component={ FormSelect }
cvalue={this.state.study.id}
onChange={value => {
this.setState({study: _.find(studies, {id: value})||{id: 0}});
return value;
}}>
{studies.map( (study, key) => ( <MenuItem key={key} value={study.id} primaryText={study.officialTitle} /> ))}
</Field>

Resources