davidkpiano / react-redux-form

Create forms easily in React with Redux.
https://davidkpiano.github.io/react-redux-form
MIT License
2.06k stars 252 forks source link

Show/hide some fields based on value of other fields #489

Closed Anarios closed 8 years ago

Anarios commented 8 years ago

I'm experimenting with the field-array example, let's say I want to add additional button for every hobby, and I want to show it only if text of current hobyy === 'show'. The Way I attempt to do it doesn't work, what would be the right way? Thanks.

p.s. remove is working, am I doing it right?

p.p.s how would it be done, if these conditions are spread between fields (visibility of field A depends on value of a field B)

       {member.hobbies.map((hobby, j) =>
          <Field model={`club.members[${i}].hobbies[${j}]`} key={j}>
            <label>Hobby #{j+1}{hobby}</label>
            {hobby === 'show' && <button type="button">Button to show on condition</button>}
            <input type="text" required />

            <button
              type="button"
              onClick={() => dispatch(actions.remove(`club.members[${i}].hobbies`, j))}
            >
              Remove Hobby
            </button>
          </Field>
        )}
davidkpiano commented 8 years ago

If you want to set a flag, then your hobby shouldn't be a plain string, right? It should be an object containing the hobby's value and a show flag, like:

hobbies[0] = {
  name: 'windsurfing',
  show: false
}

And then you can just use that flag like so:

{member.hobbies.map((hobby, j) =>
  <Field model={`club.members[${i}].hobbies[${j}].value`} key={j}>
    {hobby.show && <button />}
    // etc.
  </Field>
)}

Hope that helps! If you want to show based on other hobbies, you have full access to the hobbies from the Redux store, so just access them like you would access anything else in Redux to conditionally show other hobbies. Nothing magical there.