Home Archives Search Feed GitHub Projects About


MobX with React

Step 1: Install mobx and mobx-react

$ yarn add mobx mobx-react

Step 2: Ensure you support decorators

If you’re using create-react-app or babel7 and stage-0 you’re fine, otherwise:

$ yarn add --dev babel-plugin-transform-decorators-legacy

In .babelrc:

{
    "plugins": ["transform-decorators-legacy"]
}

Step 3: Create a store

In something like $app_root/stores/todoStore.js

import {observable} from 'mobx';

class TodoStore {
    @observable todos = [];

    function addTodo(todo) {
        this.todos.push(todo);
    }
    // ...etc
}

export default new TodoStore();

Step 4: In your application’s root, provide mobx store(s)

import React from "react";
import { Provider } from "mobx-react";
// Stores
import todoStore from "./stores/todoStore";

export default class App extends React.Component {
  render() {
    return (
      <Provider
        todoStore={todoStore}
        // add other stores here
      >
        <MainContainer />
      </Provider>
    );
  }
}

Step 5: Use stores in components

import React from "react";
import { inject, observer } from "mobx-react";

@inject("todoStore")
@observer
export default class TodoList extends React.Component {
  render() {
    const todos = this.props.todoStore.todos.map(todo => <li>{todo.name}</li>);

    return (
      <div>
        <ul>{todos}</ul>
        <button
          onClick={() => this.props.todoStore.addTodo({ name: "Another todo" })}
        >
          Add Todo
        </button>
      </div>
    );
  }
}
Posted on January 15, 2018   #QuickRef     #React     #MobX  






← Next post    ·    Previous post →