Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does redux-form field value can hold object instead of just a string?

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

like image 646
Hareesh Avatar asked Apr 28 '16 12:04

Hareesh


2 Answers

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>
    )
  }
}
like image 128
Daniel G.F. Avatar answered Oct 16 '22 10:10

Daniel G.F.


Yes, the value can be a complex object. There's even an example demonstrating it.

Complex Values Example

like image 5
Erik R. Avatar answered Oct 16 '22 09:10

Erik R.