Working in an environment with tight deadlines and a lot to do, it’s easy to see the benefits of existing libraries, kits and components. 90% of the time, if you need a problem solved, there’s already a package that solves it and has 10 thousand stars on GitHub. Forms especially have become an almost inevitable dependency. So why take on the added effort to solve a solved problem?
- It’s flexible. Project specs tend to change rapidly no matter how firmly they have been defined. Vendor components can get increasingly difficult to keep working for you.
- It can be as simple or complicated as you need, and it won’t be as bulky as a works-for-every-use-case library.
- Customisability. With every dependency, you’re adopting someone else’s conventions and design decisions. Maintaining a cohesive app where parts are designed to work together is a much more pleasant experience.
To do anything from scratch the right way is quite an undertaking. But, depending on your process and project requirements, this approach can save you both time and pain. There are a lot of ways to do this, so treat it as a demonstration rather than a prescription.
How it's done
A good place to start with developing an isolated piece of code is (a little counterintuitively) to consider its API. You could throw together a form component that accepts a configuration object and ignore inner markup and styling. So, something like this:
…could be parsed by our system into a set of fields straight off the bat. This is a very useful approach when you are building something with a lot of forms and a complicated layout isn’t really a consideration.
What I’d like to go over instead is component composition.
Anything going on within the first level of children passed down to your form is accessible and readable to it. So long as the nested components adhere to a set of simple conventions, most importantly controlled components.
What’s going on here is the Form maps its children and checks if they have a “name” prop in there set to one of the field names of the object to be mutated by the form. If they do, they are passed a value and an onChange. That’s the gist of it. You don’t even need to manage submits. The cool thing about doing it like this is that the form itself can be one big controlled component, unlike a black box that spits out its state only on submit.
You could instead of passing input components, pass a wrapper with a “type” prop. This will have the added benefit of allowing you to discriminate between components via 'child.type'.