简体   繁体   中英

Dynamic Form in React with Redux-Form

Im developing a Soccer Betting system. I want to make a form dynamically and keep the objects in the state with redux-forms.

My basic entity is a Match: Who has a home_team, a away_team, and inputs with a home_result and a away_result.

 matches = [
{
  name: 1,
  type: "group",
  home_team: 1,
  away_team: 2,
  home_result: null,
  away_result: null,
  date: "2018-06-14T18:00:00+03:00",
  stadium: 1,
  channels: [],
  finished: false
},
{
  name: 2,
  type: "group",
  home_team: 3,
  away_team: 4,
  home_result: null,
  away_result: null,
  date: "2018-06-15T17:00:00+05:00",
  stadium: 12,
  channels: [],
  finished: false
},

I want to fill it in a Redux-Form, but get stuck in the best way to make it. I want too that, every time a user changes the values on the input, this is reflected in the State-Json.

To dynamically create a form, you will need to build your data differently. You need fields object that will look like this(with the matches id):

const fieldsObject = ['match1', 'match2', 'match3']

And a initialValues object that will look like this:

const resultsObject = {
  match1_home: 1, 
  match1_away: 3
}

And so on. Then, the Form will initial its fields based on the initialValues and the names of the fields. The code:

const MyForm = (props) => {
 const { handleSubmit, fields } = props;
return (
    <form onSubmit={handleSubmit}>
      {fields.map(match => (
        <div key={match}>
          <Field
            name={`${match}_home`}
            component="input"
            />
           <Field
            name={`${match}_away`}
            component="input"
            />
        </div>
      ))}
      <button type="submit">Submit</button>
    </form>
  )
}

And the usage will look like this:

<MyForm initialValues={resultsObject} fields={fieldsObject} onSubmit={this.submitForm}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM