Does redux-form field value can hold object instead of just a string?
Consider following example
class SelectQuestions extends Component{
render(){
const {fields:{question1,question2},handleSubmit}=this.props;
return <div>
<form onSubmit={handleSumbit(this.handleFunction.bind(this))}>
<SelectQuestion {...question1}/>
<SelectQuestion {...question1}/>
<button type="submit" className="btn btn-default">Submit</button>
</form>
</div>
}
}
class SelectQuestion extends Component{
render (){
<select></select>
}
}
'SelectQuestion' takes array of Questions, each Question has question id and question name.
Once the user selects the question I wanted to to return QuesionId and QuesitonName. How it can be achieved using redux-form in react
TL:DR
Yes it can hold an object. Check out this example: https://codesandbox.io/s/vq6k6195rl
Explanation:
For a select, you can define your selects like this:
const myFancyQuestions = [
{ id: 1, label: 'Why?', category: 'Asking why' },
{ id: 2, label: 'Who?', category: 'Asking who' },
{ id: 3, label: 'When?', category: 'Asking when' }
];
Then wrap your component with Field component.
<Field component={ObjectSelect} name="myFancySelect" options={myFancyQuestions}/>
And then just show it in your render:
class ObjectSelect extends React.Component {
render() {
const { input, multiple, options, value, ...rest } = this.props;
const parse = event => {
// This is what redux-form will hold:
return JSON.parse(event.target.value);
}
return (
<select
onBlur={event => input.onBlur(parse(event))}
onChange={event => input.onChange(parse(event))}
{...rest}>
{options.map(option =>
<option key={option.id}
value={JSON.stringify(option)}
selected={input.value.id == option.id}>
{option.label}
</option>)}
</select>
)
}
}
Yes, the value can be a complex object. There's even an example demonstrating it.
Complex Values Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With