Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@slmyers
Created April 1, 2019 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slmyers/600520095de7408350135cf2e545983a to your computer and use it in GitHub Desktop.
Save slmyers/600520095de7408350135cf2e545983a to your computer and use it in GitHub Desktop.
State tracking for conditional rendering in form anti-pattern

A common situation is rendering a form input iff some condition has been met. As an example, a user selects other from a gender dropdown and a text input is rendered so they can specify.

// how we commonly address this use-case
class Example extends React.Component {
  state = { gender: null } //tracking form state in component
  onGenderChange = e => this.setState({ gender: e.target.value }) //updating form state outside of form
  render() {
    const { gender } = this.state
    return (
      <Formsy.Form>
        <select name="gender" onChange={this.onGenderChange}>
          <option value="M">Male</option>
          <option value="F">Female</option>
          <option value="O">Other</option>
        </select>
        
        {gender === "O" && <input name="other_gender" type="text" />}
      </Formsy.Form>
    )
  }
}

The problem with the above example is that we are in effect tracking and updating values when a form library does that same work.

function ImprovedExample() {
  return (
    <Form render={() => (
        <form>
          <Field name="gender" render={() => (
            <select>
              <option value="M">Male</option>
              <option value="F">Female</option>
              <option value="O">Other</option>
            </select>
          )}/>
          <Condition when="gender" is="O">
            <Field name="other_gender" render={() => <input name="other_gender" type="text" />}/>
          </Condition> 
        </form>
    )}/>
  )
}
@slmyers
Copy link
Author

slmyers commented Apr 1, 2019

Adapted from the example from the react-final-form README

https://github.com/final-form/react-final-form#conditional-fields

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment