Finding structure in react

Alpha Shuro
Mar 26, 2017 · 2 min read

After learning about React and redux I found two barriers to my adoption of them:

  • Creating and maintaining a sane folder structure.
  • Managing large forms.

Like most people, I thoroughly enjoyed redux after learning it. I used it for every project until I grew tired of the amount of boilerplate involved. I started skipping it on some components, and eventually, entire projects. This quickly came back to bite me when I started to see inconsistent state in my applications.

It can also be really tedious to build forms with more than 3 inputs while trying to stay within the bounds of the advice you receive in the React community (don’t use refs, maintain a single source of truth for state etc).

The solutions I have found to these two problems are:

  1. The feature-based folder structure
  2. Redux forms

I have adopted a folder structure organized by features rather than code.


src
- App
- index.jsx
- Nav.jsx
- LandingPage
- index.jsx
- PostsPage
- index.jsx
- NewPostForm.jsx
- PostSummary.jsx
- containers
- actions.js
- reducer.js
- NewPostForm.js

This makes adding features and managing your files easier because your files are all contained in their little bubble.

Redux forms removes all the boilerplate around handling your input events and maintaining all of them in the redux store, allowing you to focus on other parts of your code. Support for custom components makes it easily suitable for anything you want to achieve, but be weary of their documentation, I found it a bit frustrating.

Here’s a simple example of using redux forms

const validate = value => value ? undefined : 'Required';const NewPostForm = ({ handleSubmit, error }) => (
<form onSubmit={handleSubmit}>
<Field name="title"
component="input"
placeholder="Card Number"
type="text"
validate={required}
/>
<Field
name="content"
component="textarea"
rows={10}
validate={required}
/>
{ error && <span>{error}</span> }
<button>Submit new post</button>
</form>
)
export default reduxForm({
form: 'newPost',
})(NewPostForm);

Your onSubmit handler will then be called with the values when the form passes validation, and the entire form state is maintained in redux so you can easily dispatch actions using one of their action creators to manipulate it. Refer to their documentation for some more complex examples.

More From Medium

Also tagged Redux

Also tagged Redux Form

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade