I'm trying to solve "simple" react/flux architecture and I need some advice. Basically I'd like to dive in to best-practices and flux implementation.
I do have simple state-full form implemented in react.js.
Basic structure of my form is something close to
<Form>
<Input name="foo" value={this.name} onChange=... />
{items.map (i) => <Item model={i} onChange=... onRemove=... />}
<Input name="sum" value={this.sum} onChange=... />
</Form>
state is similar to
{ name: "Bar Baz", items: List.of(new ItemRecord(...)), sum: 10 }
sum
attribute of state is calculated from items
list.
NOTE: Both form/state is simplified, in real-life there are about 20 input fields.
Currently my top component <Form>
stores the current state for every input/child components. You can see that I'm providing onChange
property to <Item>
component, if user change the <Item>
component onChange
callback is called, and ItemRecord
is updated, sum is recalculated and new state is set with help of Immutability Helpers.
I hope you have got the idea, of how does it currently work.
Edit: I forgot to mention, that <Item>
component is state-less, just call parent.onChange
with some additional info.
I'd like to know if this is good approach on forms, because I was currently thinking about something little bit different based on Flux
architecture.
I'd move my state of <Form>
component outside, to the FormStore
. State (or part of it) would be represented as FormRecord
(Immutable.js record). Now, ItemRecord
should be also extracted into the ItemStore
. Also, I'd have some method e.g. getStateFromStore()
to join the data together and set as state of <Form>
.
How should I handle the changes of my <Form>
inputs ? Should I call in Input.onChange
some action to the store, which will update the FormRecord
? Once it is updated it will fire some event on which is <Form>
component listening and it will set the current state based on getStateFromStore()
?
I guess that, I should make something similar with ItemStore
as well.
What do you think, is this good approach to form implementation in react ? Or should I go state-less way (but I'd like to have live updating of sum
and some live validation in the future) and parse the state on form submit ?
What about the performance, won't be inputs laggy when users are typing in ?
Thank you for your time.
PS: Sorry for my English, I hope that you can understand the point.
It sounds like you're on the right track. Item should update the state in the store. The store then passes the state to the Form as props. The Form passes each prop to the Item. It makes sense to have one Form store. This is "one-way data flow".
No, input is not laggy. We've done a complex Web app at the level of complexity of Google docs and it's very performant. Plus, it's easy to reason about. That's what the whole point of React.