RxJs forms in React - Part 1

For a React based project I am working on I wanted to try and mimic some of the ease of use of reactive forms in Angular, thanks to rxjs. There are already some rxjs based form libraries for React,  which I may revert to using, but wanted to use this as a way of learning more about React, in particular setting up of higher order components and more complex manipulation of props.children.

The main aim is to come up with a way of declaratively setting up forms, with a minimal amount of additional props required for each field, and getting back an observable containing the form data.

Ideally adding a form should be as easy as this :


It looks like the easiest way to achieve this is to add a ref to each form field, and then use rxjs fromEvent to attach an observable to them. What I want to be able to do though is automatically attach the refs, even if the form fields are nested within other elements. It turned out to be reasonably easy to do this using, React.Children.map, React.cloneElement, and a recursive method. The first rough implementation looks like this:


By pushing each of the refs into an array, once the component is mounted the rxjs Observables can be created for each ref. Currently the form field Observables are just console logging, just to prove that the recursive adding of the refs is a viable option. The next step is to work out the best way to combine the Observables and return them in a usable way to the parent component.

Comments