Setting default value for select field in redux form - reactjs

Want to make a default option show up but doesn't seem to work no matter what I try
Already tried looking online but can't find anything that works
<Field
name="product_group"
component={renderSelectField}
label='Product Group'
defaultValue={{label: "RT", value: "RT"}}
options={this.state.options}
placeholder="Select Product Group"
multi={false}
/>
this is for rendering
export const renderSelectField = ({input, options, components, label, placeholder, disabled, multi, type, meta: {touched, error}}) => (
<div>
<label>{label}</label>
<div>
<Select
value={input.value}
onChange={input.onChange}
onBlur={() => input.onBlur(input.value)}
options={options}
components={components}
placeholder={placeholder}
onBlurResetsInput={false}
onSelectResetsInput={false}
autoFocus
disabled={disabled}
isMulti={multi}
/>
{touched && error && <span>{error}</span>}
</div>
</div>
);

Try this.
class Select extends Component {
render() {
const { name, value, onChange, error, options } = this.props;
return (
<div className="form-group">
<select
className="form-control"
id={name}
name={name}
value={value}
onChange={onChange}
error={error}
>
{options.map(option => (
<option key={option.name} value={option._id}>
{option.name}
</option>
))}
</select>
{error && <div className="text-danger">{error}</div>}
</div>
);
}
}
export default Select;
import above class in your main component. I assume you have defined this select name as "paymentOption" in state. Define your state with default value of select.
state={
paymentOption: "Receive Money"
}
payOptions = [
{ _id: "Send Money", name: "Send Money", value: "Send Money" },
{ _id: "Receive Money", name: "Receive Money", value: "Receive Money"
},
];
<Select name="paymentOption"
onChange={e =>
this.setState({
paymentOption: e.currentTarget.value
})
}
value={paymentOption} // const {paymentOption} = this.state
options={this.payOptions}
error={error}
cssClass={styles.selectList}
/>

If you put value={input.value || defaultValue } in renderSelectField component you can get it to work, but for me the it appears in the value object only after the field is touched.

Related

How to reset a react-select single-input with Formik with reset button

I am relatively new to React and especially new to both react-select and Formik. I have a form that has an Input component and three Select components. The input as well as the two selects that use isMulti for multiple selected options at once clear just fine when I use just a basic reset button, but the single select component does not. If I check what the values are they are empty, but the UI does not reflect this change. I have tried:
utilizing resetForm(), setting it to the initialValues as well as an empty object.
using onReset and implicitly calling resetForm from there.
using a few different variations of setFieldValue
I thought it might be the way my initialValues were set up, but at this point I am just going in circles and hoping a more seasoned eye can pick up on this.
(PS- the example in the docs shows you how to use React-Select with Formik with a reset button, but it does not give an example of a non-multi select.)
The single select has a name of 'paid', and I have include the object which I believe is correct using a value and a label property
simplified sandbox. desired behavior: clicking 'reset' will reset the option to the initialValues and show the placeholder text in the UI.
https://codesandbox.io/s/peh1q
const costOptions = [
{ value: 'true', label: 'Paid' },
{ value: 'false', label: 'Free' },
];
Resources.propTypes = {
initialValues: shape({
category: array,
q: string,
languages: array,
paid: string,
}),
};
Resources.defaultProps = {
initialValues: {
category: [],
q: '',
languages: [],
paid: '',
},
};
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values, actions) => {
handleSubmit(values, actions);
actions.setSubmitting(true);
}}
>
{({ isSubmitting }) => (
<Form>
<Field
data-testid={RESOURCE_SEARCH}
disabled={isSubmitting}
type="search"
name="q"
label="Search Keywords"
component={Input}
/>
<div className={styles.formContainer}>
<div className={styles.selectColumn}>
<Field
isDisabled={isSubmitting}
isMulti
placeholder="Start typing a category..."
label="By Category"
name="category"
options={allCategories}
component={Select}
/>
</div>
<div className={styles.selectColumn}>
<Field
isDisabled={isSubmitting}
placeholder="Resource cost..."
label="By Cost"
name="paid"
options={costOptions}
component={Select}
/>
</div>
<div className={styles.selectColumn}>
<Field
isDisabled={isSubmitting}
placeholder="Start typing a language..."
isMulti
label="By Language(s)"
name="languages"
options={allLanguages}
component={Select}
/>
</div>
</div>
<div className={styles.buttonGroup}>
<Button disabled={isSubmitting} type="submit">
Search
</Button>
<Button disabled={isSubmitting} type="reset">
Reset
</Button>
</div>
</Form>
)}
</Formik>
So nothing I needed to fix was actually in the code I posted (learning point taken) but it was in the codesandbox.
Select component being used in Formik looks like this:
import React from 'react';
import {
arrayOf,
bool,
func,
number,
object,
objectOf,
oneOfType,
shape,
string,
} from 'prop-types';
import { ErrorMessage } from 'formik';
import Alert from 'components/Alert/Alert';
import Label from 'components/Form/Label/Label';
import ThemedReactSelect from './ThemedReactSelect';
import styles from './Select.module.css';
Select.propTypes = {
field: shape({
name: string.isRequired,
value: oneOfType([string.isRequired, arrayOf(string.isRequired).isRequired]),
}).isRequired,
form: shape({
// TODO: Resolve why multiselects can end up with touched: { key: array }
// see ThemedReactSelect as well
// touched: objectOf(bool).isRequired,
touched: object.isRequired,
errors: objectOf(string).isRequired,
setFieldTouched: func.isRequired,
setFieldValue: func.isRequired,
}).isRequired,
hasValidationStyling: bool,
id: oneOfType([string, number]),
isLabelHidden: bool,
isMulti: bool,
label: string.isRequired,
options: arrayOf(shape({ label: string.isRequired, value: string.isRequired }).isRequired)
.isRequired,
};
Select.defaultProps = {
hasValidationStyling: true,
id: undefined,
isLabelHidden: false,
isMulti: false,
};
export default function Select({
field: { name, value: fieldValue },
form: { errors, setFieldTouched, setFieldValue, touched },
hasValidationStyling,
id,
isLabelHidden,
isMulti,
label,
options,
...props // disabled, placeholder, etc.
}) {
/**
* #description handle changing of non-multi select
* #param {string} selected
*/
const onChangeSingle = selected => {
setFieldValue(name, selected.value);
};
/**
* #description handle changing of multi select
* #param {string[]} selectedArray
*/
const onChangeMulti = selectedArray => {
if (selectedArray) {
setFieldValue(
name,
selectedArray.map(item => item.value),
);
} else {
setFieldValue(name, []);
}
};
/**
* #description Return the selected value as a string
* #returns {string}
*/
const getValueFromSingle = () => {
return options.find(option => option.value === fieldValue);
};
/**
* #description Return an array of selected values for multi selects
* #returns {string[]}
*/
const getValueFromMulti = () => {
return options.filter(option => fieldValue.includes(option.value));
};
const handleBlur = () => {
setFieldTouched(name);
};
const hasErrors = Boolean(errors[name]);
// handlers and value depend on whether or not select allows for multiple selections.
const value = isMulti ? getValueFromMulti() : getValueFromSingle();
const onChangeHandler = isMulti ? onChangeMulti : onChangeSingle;
return (
<div className={styles.field}>
<Label for={name} isHidden={isLabelHidden}>
{label}
</Label>
<div className={styles.selectFeedbackGrouping}>
<ThemedReactSelect
{...props}
hasErrors={hasErrors}
hasValidationStyling={hasValidationStyling}
isTouched={touched[name]}
id={id || name}
isMulti={isMulti}
name={name}
onBlur={handleBlur}
onChange={onChangeHandler}
options={options}
value={value}
/>
<ErrorMessage
name={name}
render={message => {
return hasErrors ? (
<Alert className={styles.errorMessage} type="error">
{message}
</Alert>
) : null;
}}
/>
</div>
</div>
);
}
Firstly, handle the null value that gets passed in handleOnChange when an input has isClearable={true} and you click the 'X' to clear the select
const onChangeSingle = selected => {
setFieldValue(name, selected === null ? '' : selected.value);
};
Then, give a fallback for the field value (in the ThemedReactSelect above)
<ThemedReactSelect
{...props}
hasErrors={hasErrors}
hasValidationStyling={hasValidationStyling}
isTouched={touched[name]}
id={id || name}
isMulti={isMulti}
name={name}
onBlur={handleBlur}
onChange={onChangeHandler}
options={options}
value={value || ''}
/>
and now the single selects work just like the multis when form is reset.
Have you tried adding the isClearable prop to the single value dropdown?
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values, actions) => {
handleSubmit(values, actions);
actions.setSubmitting(true);
}}
>
{({ isSubmitting }) => (
<Form>
//...Other Formik components
<div className={styles.selectColumn}>
<Field
isClearable={true} // <-- added this
isDisabled={isSubmitting}
placeholder="Resource cost..."
label="By Cost"
name="paid"
options={costOptions}
component={Select}
/>
</div>
<div className={styles.selectColumn}>
<Field
isDisabled={isSubmitting}
placeholder="Start typing a language..."
isMulti
label="By Language(s)"
name="languages"
options={allLanguages}
component={Select}
/>
</div>
</div>
<div className={styles.buttonGroup}>
<Button disabled={isSubmitting} type="submit">
Search
</Button>
<Button disabled={isSubmitting} type="reset">
Reset
</Button>
</div>
</Form>
)}
</Formik>

How to set state for text box in functional component

I am working on React JS. I have one text-box component and I want to show some default value in it. After that, the user should be allowed to change the value. Now I am unable to change the value. The text box is behaving like read-only. Below is my code
const EditStyleFormComponent = ({
submitting,
invalid,
}) => (
<form className={className} onSubmit={handleSubmit}>
<h2>LSPL (Low Stock Presentation Level)</h2>
<Line />
<InputGroup>
<TextFieldWithValidation name="lsplMan" label="LSPL Manual" input={{ onChnage:'', value: 'Current' }} />
</InputGroup>
</form>
);
Below is my TextFieldWithValidation code.
export const TextFieldWithValidationComponent = ({
meta,
input,
noStyles,
...otherProps
}) => (
<TextField
state={noStyles ? textFieldStates.DEFAULT : getState(meta)}
errorMessage={meta.touched ? meta.error : null}
{...input}
{...otherProps}
/>
);
Below is my TextField code.
const TextField = ({
className,
label,
description,
state,
errorMessage,
isEditable,
spaceAtBottom, // Not used, but we don't want it in otherProps
...otherProps
}) => {
const inputId = _.uniqueId();
return (
<div className={className}>
{label &&
<label htmlFor={inputId}>{label}</label>
}
<div className="input-group" id={isEditable ? 'editable' : 'readonly'}>
<input
id={inputId}
readOnly={!isEditable}
{...otherProps}
/>
{getStatusIcon(state)}
{errorMessage &&
<Error>{errorMessage}</Error>
}
{description &&
<Description>{description}</Description>
}
</div>
</div>
);
};
Can someone help me to fix this issue? Any help would be appreciated. Thanks
You can use State Hook for manage state in functional component.
Example :
const Message = () => {
const [message, setMessage] = useState( '' );
return (
<div>
<input
type="text"
value={message}
placeholder="Enter a message"
onChange={e => setMessage(e.target.value)}
/>
<p>
<strong>{message}</strong>
</p>
</div>
);
};
Yu defined onChange as empty string in EditStyleFormComponent component. So on any change input component just do nothing.
onChange should be some function that will update value.
If you want to use functional components there are two possible solutions:
Lift state up to parent component of EditStyleFormComponent (in case parent is class based component)
Use React Hooks like so (just example!)
const EditStyleFormComponent = ({
submitting,
invalid,
}) => {
const [inputValue, setInputValue] = useState ('Current'); // default value goes here
return <form className={className} onSubmit={handleSubmit}>
<h2>LSPL (Low Stock Presentation Level)</h2>
<Line />
<InputGroup>
<TextFieldWithValidation name="lsplMan" label="LSPL Manual" input={{ onChnage: (e) => { setInputValue(e.target.value); }, value: inputValue }} />
</InputGroup>
</form>
};

Formik form not updating fields upon edit

I've been trying to rewrite my beginner form in React to use Formik.
I've gotten to the state that the form is being rendered, however, for some reason, I can't update the fields. It's clear that I made a mistake somewhere that prevents Formik from updating the state. What am I missing?
An example form component:
export const TextBox: React.SFC<FieldProps<any> & CustomFormElementProps> = ({
field, // { name, value, onChange, onBlur }
form: { touched, errors },
loading,
...props
}) => (
<div className="row form-group" key={field.name}>
<label className="col-sm-2 control-label">
<ReactPlaceholder showLoadingAnimation ready={!loading} type="text" rows={1} className="control-label">
{props.label}
</ReactPlaceholder>
</label>
<div className="col-sm-10">
<ReactPlaceholder showLoadingAnimation ready={!loading} type="text" rows={1} className="form-control">
<input type="text"
disabled={props.disabled}
className="form-control"
id={field.name}
onChange={field.onChange}
onBlur={field.onBlur} {...props} />
{touched[field.name] && errors[field.name] && <span className="text-danger">{errors[field.name]}</span>}
</ReactPlaceholder>
</div>
</div>
);
The form is initialized in another component (which acts as a page template for the website);
renderFormElements() {
var formFields = this.props.detailsElements.map((item) => {
switch (item.type) {
case FormElementType.TextLine:
return <TextLine
name={item.name}
label={item.label}
disabled={!this.state.editMode}
loading={item.loading}
value={item.defaultValue}
key={'TextBox_' + item.name}
/>
case FormElementType.TextBox:
return <Field
type="text"
name={item.name}
label={item.label}
component={InputElements.TextBox}
disabled={!this.state.editMode}
loading={item.loading}
value={item.defaultValue}
key={'TextBox_' + item.name}
/>
case FormElementType.DropDown:
return <Field
name={item.name}
label={item.label}
component={InputElements.DropDown}
disabled={!this.state.editMode}
loading={item.loading}
value={item.defaultValue}
options={item.options}
key={'DropDown_' + item.name}
/>
case FormElementType.RadioGroup:
return <Field
type="radio"
name={item.name}
label={item.label}
component={InputElements.RadioGroup}
disabled={!this.state.editMode}
loading={item.loading}
value={item.defaultValue}
options={item.options}
key={'RadioGroup' + item.name}
/>
}
});
var initialValues:{ [k: string]: any } = {};
this.props.detailsElements.map((item) => {
initialValues[item.name] = item.defaultValue;
})
console.log(initialValues);
var formSection =
(<Formik initialValues={initialValues} onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2))
actions.setSubmitting(false)
}, 1000)
}}>
<Form key="mainForm">
{formFields}
</Form>
</Formik>)
return formSection;
I was assuming that the onChange event handler was taken care of by Formik, and that, if I didn't want to do special stuff, I did not need to provide anything to this.
What am I missing here?
Thanks!
your formFields function gets all of Formik props goodies.
it contains handleChange - use this handler as your on change.
Also, make sure the field "id" is the same as the values key.
const {
values,
touched,
errors,
dirty,
isSubmitting,
handleChange,
handleBlur,
handleSubmit,
} = this.props;
<FormControl
id="username"
required
placeholder="Enter Username"
value={values.username}
error={touched.username && errors.username}
onChange={handleChange}
onBlur={handleBlur}
/>
try putting the name attribute in the input element
name is what you got from field.name

redux form dynamic categories

i am using redux form and what i do here is when user selects category the next select field should have all subcategories depending of category selected.
what i did was i created api for fetching all categories, i trigger action via componentWillMount and load all categories in first categories select field, then i use formValueSelector of redux-form to get selected category to the state/this.props, then i use componentWillReceiveProps() to trigger fetching subcategories with that e.g. "this.props.categoryId" that i put to state with formValueSelector and that works.
and my question is, is this the right aporoach, is there a better way?
and the second question, is how do i reset categoryChildId field to, lets say blank when the categoryId field is changed?
import React from 'react';
import moment from 'moment';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import { connect } from 'react-redux';
import { Link, NavLink } from 'react-router-dom';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import * as actions from '../../actions/category';
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<input {...input} placeholder={label} type={type} />
{touched &&
error &&
<div className="error">{error}</div>}
</div>
)
const renderTextArea = ({ input, label, type, meta: { touched, error } }) => (
<div>
<textarea {...input} placeholder={label} type={type} />
{touched &&
error &&
<div className="error">{error}</div>}
</div>
)
class AddProduct extends React.Component {
constructor(props) {
super(props);
this.state = {
value: `${process.env.SITE_URL}/user/${props.user.username}`,
copied: false,
isLoading: false
};
}
componentWillMount() {
this.props.startSetCategories()
}
componentWillReceiveProps(nextProps) {
this.props.startSetCategoryChildren(nextProps.categoryId)
console.log(nextProps)
}
renderCategorySelector = ({ input, meta: { touched, error } }) => {
return (
<div>
<select {...input}>
<option value="">select category</option>
{!this.props.categories ? (
<option value="">loading...</option>
) : (
this.props.categories.map(category => <option value={category._id} key={category._id}>{category.name}</option>)
)
}
</select>
{touched && error && <span>{error}</span>}
</div>
)
}
renderCategoryChildSelector = ({ input, meta: { touched, error } }) => {
return (
<div>
<select {...input}>
<option value="">select sub category</option>
{!this.props.categoryChildren ? (
<option value="">loading...</option>
) : (
this.props.categoryChildren.categoryChildren.map(categoryChild => <option value={categoryChild._id} key={categoryChild._id}>{categoryChild.name}</option>)
)
}
</select>
{touched && error && <span>{error}</span>}
</div>
)
}
submitForm = values => {
console.log(values)
}
render() {
const username = localStorage.getItem('username');
const { user } = this.props;
const { handleSubmit, pristine, submitting, categoryId } = this.props;
return (
<div className="profile-wrapper">
<div className="profile">
<form className="profile-addproduct-left" onSubmit={handleSubmit(this.submitForm.bind(this))}>
<div className="profile-addproduct-title">
<h2>New Product</h2>
<p>Fill out the form.</p>
</div>
<div className="profile-form-group">
<div className="profile-form-item">
<p>Title</p>
<Field
name="title"
type="text"
label="title of a product"
component={renderField}
/>
</div>
<div className="profile-form-item">
<p>Category</p>
<Field
name="categoryId"
type="text"
component={this.renderCategorySelector}
label="category"
/>
{this.props.categoryId ?
<Field
name="categoryChildId"
type="text"
component={this.renderCategoryChildSelector}
label="categoryChild"
/> :
''
}
</div>
<div className="profile-form-item">
<p>Description</p>
<Field
name="description"
type="text"
label="Write some interesting..."
component={renderTextArea}
/>
</div>
</div>
<div className="profile-addproduct-form-submit">
<button className="button button--register" type="submit" disabled={this.state.isLoading || pristine}>Submit New Product</button>
</div>
</form>
</div>
</div>
)
}
};
AddProduct = reduxForm({
form: 'addproduct-form'
})(AddProduct)
const selector = formValueSelector('addproduct-form')
AddProduct = connect(state => {
const categoryId = selector(state, 'categoryId')
return {
categoryId,
categories: state.category.categories,
categoryChildren: state.category.categoryChildren
}
}, actions)(AddProduct)
export default AddProduct
You should not call the startSetCategoryChildren (or any other api) in componentWillReceiveProps... because it would call every time whenever componentWillReceiveProps called
componentWillReceiveProps(nextProps) {
this.props.startSetCategoryChildren(nextProps.categoryId)
console.log(nextProps)
}
Instead of this you can to do this on handleChange of the Field
<Field
name="categoryId"
type="text"
component={this.renderCategorySelector}
label="category"
onChange={(e) => this.props.startSetCategoryChildren(e.target.value)}
/>

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