Steps to creating a React component
This is taken from the React documentation: https://facebook.github.io/react/docs/thinking-in-react.html
1. Identify the different components
Data flow goes from parent to children. It’s important to know break down components so you can better understand how data flows and is inherited through each component
Here is the breakdown of components
1. FilterableProductTable (orange): contains the entirety of the example
2. SearchBar (blue): receives all user input
3. ProductTable (green): displays and filters the data collection based on user input
4. ProductCategoryRow (turquoise): displays a heading for each category
5. ProductRow (red): displays a row for each product
2. Build a static version using raw data
The next step is build a static version using raw data. I like to copy and paste a JSON response and create an array to use.
I always start with the parent component and work my way down. This is how I imagine the data flow, so I find it helpful to follow this same pattern, especially when passing down props. However, it depends on how large of a project it is. For bigger products, it is better to go bottom-up and write tests along the way.
Don’t use setState unless you’re working with interactive data. When trying to build your static version, just use props.
3. Identify what type of interactions will cause your component to change
This is where we bring in setState to determine how our component changes based on interactivity.
Starting out , here is the data we have:
– The original list of products
– The search text the user has entered
– The value of the checkbox
– The filtered list of products
To determine which of these applies to state, ask yourself 3 questions:
1. Is it passed in from a parent via props? If so, it probably isn’t state.
2. Does it remain unchanged over time? If so, it probably isn’t state.
3. Can you compute it based on any other state or props in your component? If so, it isn’t state.
With that, our final state are only two things:
1. The search text the user has entered
2. The value of the checkbox
4. Identify where state should live
Once you find all of the components that are affected by state, then find a parent object to put state in.
This is the concept of uni-directional data flow in React. By finding a common parent, it can store changes to state and pass that change as props to the child elements.
5. Identify how to pass state back up to the parent object
The best way to do this is to pass a callback down from the parent to the child components. That callback will fire whenever the the state is updated.