Organize a Large React Application and Make It Scale

Organize a Large React Application and Make It Scale

☞ 

#reactjs

  • In this article, I’ll talk you through the decisions I make when building React application: picking tools, structuring files, and breaking components up into smaller pieces.
  • Once you’ve done that you can always import files relative to the directory:

    Whilst this does tie your application code to Webpack, I think it’s a worthwhile trade-off because it makes your code much easier to follow and imports much easier to add, so this is a step I’ll take with all new projects.

  • For example, we have a folder called that contains all components relating to the shopping cart view, and a folder called that contains code for listing things users can buy on a page.
  • Following on from the previous rule, we stick to a convention of one React component file, and the component should always be the default export.
  • Normally our React files look like so:

    In the case that we have to wrap the component in order to connect it to a Redux data store, for example, the fully wrapped component becomes the default export:

    You’ll notice that we still export the original component; this is really useful for testing where you can work with the “plain” component and not have to set up Redux in your unit tests.

I’ll talk you through the decisions I make when building React applications :picking tools, structuring files,and breaking components up into smaller pieces
Continue reading “Organize a Large React Application and Make It Scale”

How to Build a Todo App Using React, Redux, and Immutable.js — SitePoint

  • This helps us get a feel for what we’re going to need our components to render:
    const dummyTodos = [
    { id: 0, isDone: true, text: ‘make components’ },
    { id: 1, isDone: false, text: ‘design actions’ },
    { id: 2, isDone: false, text: ‘implement reducer’ },
    { id: 3, isDone: false, text: ‘connect components’ }
    ];

    For this application, we’re only going to need two React components, Todo / and TodoList /.

  • js

    import React from ‘react’;

    export function Todo(props) {
    const { todo } = props;
    if(todo.isDone) {
    return strike{todo.text}/strike;
    } else {
    return span{todo.text}/span;
    }
    }

    export function TodoList(props) {
    const { todos } = props;
    return (
    div className=’todo’
    input type=’text’ placeholder=’Add todo’ /
    ul className=’todo__list’
    {todos.map(t = (
    li key={t.id} className=’todo__item’
    Todo todo={t} /
    /li
    ))}
    /ul
    /div
    );
    }

    At this point, we can test these components by creating an index.html file in the project folder and populating it with the following markup.

  • /components’;

    const dummyTodos = [
    { id: 0, isDone: true, text: ‘make components’ },
    { id: 1, isDone: false, text: ‘design actions’ },
    { id: 2, isDone: false, text: ‘implement reducer’ },
    { id: 3, isDone: false, text: ‘connect components’ }
    ];

    render(
    TodoList todos={dummyTodos} /,
    the code with npm run build, then navigate your browser to the index.html file and make sure that it’s working.

  • Our dummy data is a great place to start from, and we can easily translate it into ImmutableJS collections:
    import { List, Map } from ‘immutable’;

    const dummyTodos = List([
    Map({ id: 0, isDone: true, text: ‘make components’ }),
    Map({ id: 1, isDone: false, text: ‘design actions’ }),
    Map({ id: 2, isDone: false, text: ‘implement reducer’ }),
    Map({ id: 3, isDone: false, text: ‘connect components’ })
    ]);

    ImmutableJS maps don’t work in the same way as JavaScript’s objects, so we’ll need to make some slight tweaks to our components.

  • The mapStateToProps function takes the store’s current state as an argument (in our case, a list of todos), then it expects the return value to be an object that describes a mapping from that state to props for our wrapped component:
    function mapStateToProps(state) {
    return { todos: state };
    }

    It might help to visualize this on an instance of the wrapped React component:
    TodoList todos={state} /

    We’ll also need to supply a mapDispatchToProps function, which is passed the store’s dispatch method, so that we can use it to dispatch the actions from our action creators:
    function mapDispatchToProps(dispatch) {
    return {
    addTodo: text = dispatch(addTodo(text)),
    toggleTodo: id

Dan Prince shows how to build a Todo app using React, Redux, and Immutable.js.
Continue reading “How to Build a Todo App Using React, Redux, and Immutable.js — SitePoint”

Why build your forms with Redux Form – DailyJS – Medium

Why build your forms with #Redux Form:  #ReactJS

  • Why build your forms with Redux FormWhen I usually create forms for my React/Redux applications I tend to keep the value of the inputs on the application state, with little to no editing, (because my forms are usually simple), I never stopped to realize what that means.
  • It also receives an event handler that will update the state when the user interacts with it.It means that when the user types the letter “J” on the input, what is visible is not the same “J”, it may be an identical “J” that comes from the state, or whatever the event handler has put in there.Ok but, that doesn’t answer the first questionBy having all the application state in the JavaScript app and using controlled components we get a single source of truth and take full control over the application behavior.In the context of a form, our React component is able to:do instant validation;control the input value format;enable, disable, show or hide components given the state;handle dynamic inputs.Although it is highly recommended to use controlled components, it is also good to point the drawback that you will have to create event handlers for all your inputs and that may be a bunch of code that doesn’t make sense to the application.What about Redux Form?Now that is known why to keep the form data in the state and you reason if that makes sense for your application we can come back to our main subject.
  • It keeps track of all common application form state such as:The fields that are in the form;The values of each field;The focused field;If the field values are valid;The fields that the user have interacted with;If the form is being submitted;If is happening any asynchronous validation.Let’s take a look at a bit of code and see how to do a setup.Here we connect the form component to Redux by decorating it with the high-order component reduxForm.
  • It will also hand us the handleSubmit function, which will take care of the submission behavior.The Field component takes our input component as its props and acts as a container, bringing the application state to the input component and binding the event handlers to update the state in store.Look at the InputText component to see the props we receive from the Field.One important point is that it’s still a developer’s responsibility to write the form and inputs components, this way the library does not take the flexibility from you to manage the behaviors of your form the way you want, or even add custom ones.And to finish our integration we add a reducer that will handle the state changes of your form.Simple isn’t it.Just one more point.
  • Look that the default value of the input is defined when the high-order component reduxForm is called and comes to the input within the prop input and not from the react’s prop defaultValue, this way we guarantee that our form values are all represented in the application state.In summary, having all your form data in application state gives you control over its behavior and you can easily implement that on a React/Redux application with Redux Form.I have created a repository on GitHub with the implementation above.

When I usually create forms for my React/Redux applications I tend to keep the value of the inputs on the application state, with little to no editing, (because my forms are usually simple), I never…
Continue reading “Why build your forms with Redux Form – DailyJS – Medium”

Redux unit testing with Jest – Ben Garrison – Medium

Redux unit testing with Jest  #react #facebook #redux #jest #javascript #reactjs

  • We are going to begin with testing a very simple Action creator.
  • If you are not familiar with the difference between Actions and Action creators, read this.actions.jsHere is an actionsJS file with a single const SET_SELECTED_ACCT and and Action Creator: setSelectedAccount().
  • This is the Action creator that we will be testing.actions.jstest.jsThis is our test file.
  • We import everything from our actions.js file, set a fake accountNumber to test with and then begin our test.
  • Line 5 and 6 describe our test(you could put multiple it tests inside of a describe), line 8 begins our mocked expected response and line 12 executes our action and uses a toEqual matcher to make the comparison of received vs expected.Your terminal will output something like the following upon success, if errors there will be context for the failure in the terminal.watch options results

If you are bootstrapping your react apps with create-react-app you may be aware that Jest is now baked in. Jest is yet another FB creation that aims to simplify writing javascript unit tests. It’s…
Continue reading “Redux unit testing with Jest – Ben Garrison – Medium”

Power of #TypeScript for #React part 3 is ready 🚀 Today looking at Actions #JavaScript…

  • Actions are a really helpful way to create separation between the different layers of an application, because they are not tightly coupled each layer can be built and tested in pieces.
  • It does bring it’s challenges however, whilst the code is loosely coupled, all areas of the code which interact with the action need to have the same expectation of it’s structure.
  • At Seccl all our actions follow the same basic structure and TypeScript allows us to define what that is by using an .
  • So now that we know the flavours, let’s look at an example of our action interface in the wild.
  • What we will create is an interface which describes the called and an action creator which builds the action.

Frontend leadership, Frontend architecture, HTML(5), JavaScript (OOJS, ES6, TypeScript), CSS (BEM, Less, SASS, Stylus), Testable Code (Mocha, Sinon, Chai, Karma), NodeJs (Express, Mongoose) , Cloud Applications (Heroku, S3, Azure)
Continue reading “Power of #TypeScript for #React part 3 is ready 🚀 Today looking at Actions #JavaScript…”

Redux-saga + React native – psak-works – Medium

Redux-saga + React native  #reduxsaga #redux #tech #react #reduxthunk #reactjs

  • The middleware was designed keeping in mind that a component should just dispatch the action and not have any concern whatsoever as to what happens after.Consider the cycle with saga:side effects with sagaSince the middleware sits separate from the components, its important that these saga files are run in the very start of the app (just like reducers).
  • /saga’;export default function* root_saga() { yield [ fork(getFlight) ];}When an event fires in the child component, then all it has to do is dispatch the action and not worry about what happens action that has the action creator getFlight()const mapDispatchToProps = (dispatch) = { return { onClick: (props) = { dispatch(getFlight()) } }}The action creator getFlight() has a type: GET_FLIGHT.
  • //action.jsexport const GET_FLIGHT = ‘GET_FLIGHT’// action creator is getFlightexport function getFlight() { return { type: GET_FLIGHT };}Now that the action is dispatched, the saga watching for GET_FLIGHT, kicks off and performs the required async action.
  • then((responseJson) = { return responseJson; })};export function* getFlight() { try { yield take(GET_FLIGHT); const flights = yield call(fetchFlights); //1 yield put({type: ‘FLIGHTS_LOADED’, flights}); //2 } catch(error) { yield put({type: ‘FLIGHTS_LOADED_FAILED’, error}); }}The getFlight() saga is ready to take ‘GET_FLIGHT’ action dispatched from the action creator.
  • //reducer.jsexport default function reducer(state, action) { switch(action.type) { case ‘FLIGHTS_LOADED’: return Object.assign({}, state, { flights: action.flights }) default: return state; }}Hence it is very essential to insert a yield where you want the middleware to stop the saga from going forward.

Yepp, thats what I thought initially. After exploring further, I started to like how saga played along with my react-redux application. So what is saga? and why saga? The way I’d like to think of it…
Continue reading “Redux-saga + React native – psak-works – Medium”

How to Organize a Large React Application and Make It Scale — SitePoint

  • In this article, I’ll talk you through the decisions I make when building React applications: picking tools, structuring files, and breaking components up into smaller pieces.
  • /lib/baz’

    When you’re building your app with Webpack you can tell Webpack to always look in a specific directory for a file if it can’t find it, which lets you define a base folder that all your imports can become relative to.

  • For example, my top level folder structure often contains:
    – src = app code here
    – webpack = webpack configs
    – scripts = any build scripts
    – tests = any test specific code (API mocks, etc)

    Typically the only files that will be at the top level are index.html, package.json, and any dotfiles, such as .

  • Normally our React files look like so:
    import React, { Component, PropTypes } from ‘react’

    export default class Total extends Component {

    }

    In the case that we have to wrap the component in order to connect it to a Redux data store, for example, the fully wrapped component becomes the default export:
    import React, { Component, PropTypes } from ‘react’
    import { connect } from ‘react-redux’

    export class Total extends Component {

    }

    export default connect(() = {…})(Total)

    You’ll notice that we still export the original component; this is really useful for testing where you can work with the “plain” component and not have to set up Redux in your unit tests.

  • Although we don’t recognize it by splitting them into folders, you can broadly split our app into two types of components:
    “smart” components that manipulate data, connect to Redux, and deal with user interaction
    “dumb” components that are given a set of props and render some data to the screen
    You can read more about how we aim for “dumb” components in my blog post on Functional Stateless Components in React.

Jack Franklin describes a set of tips and best practices for creating and organizing React applications in a scalable way.
Continue reading “How to Organize a Large React Application and Make It Scale — SitePoint”