Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, July 27, 2017

React + Redux

Last time I showed how React components use props and states which are passed down and up to reach all the app and connect everything.
Now, what if we could have the state of the whole app in a single global object?
That is what makes Redux work best with React.
For this example, I have an input that creates rows in a table. The rows can be deleted and there is an undo and redo buttons that only go one step behind/forward. Simple enough.
Let’s see how can I apply Redux for this.

Redux stores the current state of the application in a global Javascript object. This is referred as the store.

This is the first of the three core elements of Redux: the store, the actions, and the reducers.

The stored state cannot be set implicitly, it can only change by dispatching actions.
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them using store.dispatch().
Actions are plain JavaScript objects. They have a type property that indicates the type of action being performed. Types are usually defined as string constants.

I identify 4 actions for this example:
  • UNDO
  • REDO

Other than types, you can use other properties to send data to the store. In this example, I send all Match data in the ADD_MATCH action as properties.
Actions have no logic. They are just signals that tell the app that something happened. The ones responsible for handling what the action does are the reducers.

Reducers receive the current state and an action and return the new state. That’s it. Nothing magical about it. Depending on the action type you take the current state and the action object and its properties to calculate the next state.
This makes for some pretty cool interactions. For this example, I save the current state as three separate objects, each of them a pseudostate of their own.
const state = {
  past: [],
  present: [],
  future: []
Like this, I can store the past, present and future state of the app in the store Object. Each one will have a list of the elements on the table at any given moment of the app’s life.

Once I have this, and if I manipulate it correctly, I can easily go back to a past state with an undo action and undo the undo action with a redo action. You can even bind the keys Ctrl+ Z for the dispatch undo function!

Now, every time I call the action dispatcher to create a Match I will have to store the current present state as the new past state. Then add the new Match to the current present state and save it as the new present state. The future state can not be known at this point, so I’ll have to save the new future state as empty. The same logic applies to removing a Match.

The only time I save a future action is when the undo action is called. The current present state is saved as the future state. Then the past state will be the new present state.

It may seem a bit confusing, but with a bit of practice and coding, you will be able to understand the state-time continuum of Redux!

The rest is just like last time, React components for everything. The only difference is that the main render method needs to be saved as a constant and subscribed to the Redux store object so that changes made in the state will affect all the components.

See the Pen DotaCraft React+Redux example by Ferdinand (@ferdibranch) on CodePen.
Play as much as you want!

Monday, June 26, 2017

Getting started with React

  Building reusable components with React

React creates components that render themselves using their own properties (props) and states (state). Using these components you can create reusable, robust and dynamic state elements for your HTML.


The first thing you would want to do is create a mock of the screen you want to build. From here you can start by drawing boxes around every component and sub-component you think you may need. The more you play around with React the better you will become at identifying what is a component and the best hierarchy they should follow.

I single out 6 components:   
  • FilterablePlayersTable: contains the entirety of the example
  • PlayerTable: renders the table
  • PlayerRow: renders each row of the table
  • SearchArea: receives all user input
  • FilterRace: area that contains the Race filter check boxes
  • FilterRaceCheckbox: the checkbox for filtering by race

The hierarchy would look something like this:

  • FilterablePlayersTable (blue)
    • PlayerTable (green)
      • PlayerRow (teal)
    • SearchArea (yellow)
      • FilterRace (orange)
        • FilterRaceCheckbox (pink)
You could make a case that the table headers could be their own component if we wanted to, for example, order by each column on click. For this basic example, I won’t be doing that. By the end of this post, you should be able to add that functionality on your own, if you feel like it.
Now that I have the component hierarchy, it’s time to build the initial static version of the app. For now, I just want to render the components. As React docs say: building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing.
For the table, I’ll use Jack Rugile’s style, because it looks cool. Except with no blur effect on hover.
You can start building top-down or bottom-up. This means starting with the highest hierarchy component (FilterablePlayersTable) or starting by the lowest hierarchy component (PlayerRow or FilterRaceCheckbox).
I prefer to build bottom-up, as every new component depends on the one just created before it and you can easily write tests for each individual component.
As each React.Component renders itself, each will have its own render() method. This is where we put the HTML code that the component will have on the page. The way React works you can render common HTML stuff, like divs, or you can render other React components.
Once the components have their proper render methods, the general outlook of the app is ready. All changes we make from here on out will not alter this structure, only improve it.
See the Pen UI DotaCraft React Example by Ferdinand (@ferdibranch) on CodePen.
React is so good at reusing components that you can easily add new stuff with minimal effort.
For example, try editing this CodePen. Go to the hard coded array RACES that represents the server input. Now try adding a new String to the array. Once the Pen re-compiles you will see that a new checkbox has been created with the value you just added. React magic.


Now that we have working visuals, it’s time to work on the functionality.
React uses two main things: props and states. Props can be passed down to child components and are usually used for rendering specific values, like data on a table row.
In this case, each row will render a specific Player from the JSON we receive so this prop will have to be passed down to PlayerTable, where I can iterate over the Players and create a PlayerRow for each and every one of them.
These props are immutable. The only time a Player’s data will change is when a new JSON array is received.
For changing values, we use “states”. In this case, the components that will be changing over time are the filters. The table will change according to the filter’s states, so the actual state will have to be saved on the highest shared parent (in this case FilterablePlayersTable) so that it can be passed down from the check boxes to the table.
What I want to do is filter the table by name with the input text field and filter the table by race when a race check box is changed.
To achieve this I will have to bind a function to a prop. React lets me do this. So now I bind a function that sets a prop of the SearchArea component as the input of the text field to the onChange event of the HTML Input element. Remember when I said that props were not supposed to change? The exception is when you need to pass the value to a parent. On the parent component, I can create a function that handles the change in state and assign it to the prop I just changed in the SearchArea. I can just keep chaining props and functions until I reach the shared parent component needed to pass down the state to the table.
For the reverse path, I send down the state to the child components until I reach the table.
On the render method, I apply the logic to filter the table according to the state I receive.  
See the Pen DotaCraft React Example by Ferdinand (@ferdibranch) on CodePen.
And there we go! All components are rendered and functional. Try adding a new Race to the initial input and add a new entry to the players with that race. You will see that the checkbox filter works perfectly.
Next time I’ll review how to integrate this component oriented front end to some backend framework.