How to use a select input type with redux-form?
Here's an example of a simple select field from the official docs:
<div>
<label>Favorite Color</label>
<div>
<Field name="favoriteColor" component="select">
<option></option>
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</Field>
</div>
</div>
Your implementation does not have option
s mapped, so select
does not work.
Sidenote
To pass initial values you should add initialValues
property to your reduxForm configuration instead of adding value
attribute to the field. Example below:
export default reduxForm({
form: 'profile',
validate: validateProfileForm,
initialValues: { ... }
})(ProfileForm);
select rating example : redux-form
example how to handle selection in redux-form
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
/*------- connect react with redux --------*/
import { connect } from 'react-redux';
/*------- action which all data to data base --------*/
import { addProduct } from '../actions'
/*------- redux form --------*/
import { Field, reduxForm } from 'redux-form';
class Form extends Component {
//PRISTINE / DIRTY // TOUCHED / ERROR : events in redux-form
/*------- renderSelectField --------*/
renderSelectField(field){
const className = `form-input ${field.meta.touched && field.meta.error ? 'has-error':''}`;
return(
<div className={className}>
<label>{field.myLabel}</label>
<select {...field.input} >
{field.children}
</select>
<div className="error">
{field.meta.touched ? field.meta.error:''}
</div>
</div>
)
}
/*------- onSubmit() : runs on submit --------*/
onSubmit(values){
// const error = this.validate(values);
// console.log(error)
console.log(values)
this.props.dispatch(addProduct({
values
}))
}
render(){
return(
<div className="Form">
<div className="top">
<h3>Add a Message</h3>
<Link to="/">Back</Link>
</div>
<form onSubmit={this.props.handleSubmit((event)=>this.onSubmit(event))}>
<Field
myLabel="Select Rating"
name="rating"
component={this.renderSelectField}>
<option></option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</Field>
<button type="submit">Submit</button>
</form>
</div>
)
}
}
/*------- validate() : validates our form --------*/
function validate(values){
const errors = {};
if(!values.rating){
errors.rating = "The rating is empty"
}
return errors;
}
/*------- it returns messages when action is called and state going to change --------*/
function mapStateToProps(state){
return {
product: state.data
}
}
/*------- reduxForm : connects redux-form with react form --------*/
export default reduxForm({
validate,
form:'AddProduct',
})(
connect(mapStateToProps,{addProduct})(Form)
)