I have created a very big(500loc, It its very big and difficult to reason about) react class. Its an autocomplete. Whats the recommended way to split this up with react/reflux. Add the logic to som services? What is best practise. I have Stores but as I understand they shouldn't contain view logic.
It's difficult to be specific to your case given that you haven't provided the code behind your component, but if I were to develop an autocomplete component I would do it as follows.
Facebook's Thinking in React guidelines suggest to break down your UI into components that represent a single aspect of your data model:
In your case, you could implement the following hierarchy:
AutoComplete
|
--AutoCompleteInput
|
AutoCompleteResults (list of results)
|
--AutoCompleteResult (individual result)
So at a very high level... AutoComplete.jsx: [...]
render() {
return (
<div>
<AutoCompleteInput />
<AutoCompleteResults />
</div>
);
}
AutoCompleteInput.jsx:
[...]
updateQuery(e) {
// FYI - you should ideally throttle this logic
autoCompleteActions.updateQuery(e.target.value);
}
render() {
return <input onChange={this.updateQuery} />
}
AutoCompleteResults.jsx:
[...]
onStoreUpdated() { // hypothetically invoked when store receives new data
this.setState({
results: productListStore.getResults()
});
}
render() {
const { results } = this.state;
const children = results.map(result => {
return <AutoCompleteResult result={result} />
});
return (
<ul>
{children}
</ul>
);
}
You're correct to state that stores should not contain view logic, but they are allowed to store both general app state and data that's resulted from an XHR, for example. In the above example, the autoCompleteActions.updateQuery
would consume a data service method to get the autocomplete options for the specific query. The success callback would then be responsible for passing the returned data to the store. The store should ideally notify subscribed components that it has received new data.
Although this is a simple overview, the result is that the components driving the AutoComplete functionality are broken down to respect single responsibilities, which should simplify your testing.