DEV Community

Ben Junya
Ben Junya

Posted on

Local State Forms in React

From the last couple of companies I've worked at, freelance and full time, I've ported by own little React Forms library and introduced them to every team I've worked on. It's small, agnostic, and straightforward, allows one to do client-side and server-side validations, showing errors through the parent component rendering it.

Here's a little bit of what it looks like:

import React from 'react';
import FormManager from '../component/FormManager';
import { InputField, RadioButtonField } from '../component/FormManager/Fields';

class IndexPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      errors: {}
    };
  }

  onFormInput = values => {
    // Your own validation stuff happens here.
    // If there's an error, you do this:
    /*
      this.setState({ errors: { password: 'Incorrect password' } });
    */
  }

  onSubmit = values => {
    // Handle submit logic here!
  }

  render() {
    <div>
      <FormManager errors={this.state.errors} onValueChange={this.onFormInput} onSubmit={this.onSubmit}
        <InputField name="username" />
        <InputField name="password" type="password" />
        <p>Take me to:</p>
        <RadioButtonField 
          name="next_view" 
          value="dashboard" 
          label="Dashboard"
        />
        <RadioButtonField 
          name="next_view" 
          value="account_page" 
          label="My Account Page" 
        />
      </FormManager>
    </div>
  }
}

Thing is, I'd love to release this open source, but looking at Formik, it's extremely popular with over 10k stars, and my library definitely doesn't have the bells and whistles that come with Formik. I just wanted to make my own tool that requires minimal boilerplating and is easy to look at, just by looking at the code.

If anything, I'd call it Reforma - A Local-State driven approach to forms in React.

What do you guys think?

Top comments (1)

Collapse
 
portela828 profile image
Flavio Portela

I think it's a good idea, feel like the core idea here is to just simplify the process of building a form, leaving the logic ( validation, error handling, etc ) in the hands of the developer, which is what many people is looking for. IMO if you want to know if people will use it there's only one way to know - SHIP IT! :D