Swizec Teller - a geek with a hatswizec.com

    Simple MobX-driven modals

    Continuing from yesterday's article about using MobX with create-react-app, we're going to build a simple MobX-driven modal. Why? Because I just did it at The Day Job™, and I think it's neat.

    If you don't think it's neat, that's okay. It's neat anyway.


    You can see the full code on GitHub here. There's a link to a compiled&hosted version. I'm still figuring out why the component inception from the gif doesn't work after compiling. Let me know if you have any ideas.

    We're going to build a modals system that lets you:

    • easily open a modal from anywhere in the code
    • specify general modal styling/behavior just once
    • define modal contents at call point
    • tie modals to URLs if needed

    All of this might sound easy to you, but it's harder than it looks. It sounds easy, and it's frustrating as hell every damn time you do it. I've done it more times than I dare count.

    MobX with React has been the easiest and most flexiblest approach I've ever used.

    You start with a store.

    // src/App.js for example purposes
    class Store {
    @observable modal = {
    show: false,
    body: null,
    @action showModal(body) {
    this.modal.show = true;
    this.modal.body = body;
    @action closeModal() {
    this.modal.show = false;
    this.modal.body = null;

    Your real life data store would be bigger and have more properties and more actions. This is an example.

    We have an @observable property modal, which has a boolean to denote whether the modal is shown, and a variable for the modal body. Ideally, it's a React component, but you can use anything that React's engine knows how to render.

    MobX uses the @observable decorator to create deep getters and setters for object properties. This allows the MobX engine to know when properties are dereferenced (read or set), and run relevant observers.

    We use the @action decorator to say that a function is an action. I don't know if this does anything practical, but it makes your code better.

    If you only change store properties in actions, then you can model your application as a state machine. If you can model your application as a state machine, then you can understand what it's doing and your life will be easier.

    Limiting yourself to performing changes in actions increases boilerplateiness a little tiny bit, and gives you this in return:

    Trust me, you want it. ?

    In App.js, you add a helper function or two. These aren't necessary, but make the markup code cleaner. You'll see.

    // src/App.js
    class App extends Component {
    store = new Store();
    // this is useful for debugging only
    componentDidMount() {
    window.store = this.store;
    openModal1() {
    this.store.showModal(<strong>Strong Hello</strong>);
    openModal2() {

    Note that your App must be an @observer. This allows the MobX engine to infer which data store changes are interesting to your component.

    In our example, the openModal functions invoke the this.store.showModal action and give it some JSX as the modal body. That's the nice thing about HTML as a first-class citizen: You can pass it around any way you want. Neat ?

    For the modal component itself, we're using simple-react-modal because it's got a clean API and makes it easy to override the styling. Ask your designer; I'm sure they want custom styling if they can get it.

    // src/App.js -> render()
    <a onclick={this.store.closeModal.bind(this.store)} style={closeStyle}>

    We're deferring to simple-react-modal to provide the Modal component and take care of the basic styling. Dark backdrop, centered white rectangle, that sort of thing.

    We tell it to show itself via the show prop, which we feed straight from our data store. To close our modal, we use the store.closeModal action, which sets show to false. Isn't that cool? Flipping a boolean makes a modal show or hide.

    For full flexibility, we use this.store.modal.body to render the modal's body. React makes it easy to store just about anything in that property. Even <App /> itself… but only in debug mode ?

    And… yeah… that's about it, really. You can open modals from anywhere in your application that has access to the data store. Call store.showModal(<stuff>), and it shows up. Call store.closeModal(), and it goes away.

    You could tie it to your routing and make it so users can refresh the page and keep the modal. I wish more webapps did that.

    PS: if you put the store in window, you can call actions in your browser console and see how your app reacts.

    Did you enjoy this article?

    Published on October 28th, 2016 in coding, Front End, MobX, react, reactjs, Technical

    Learned something new?
    Want to become an expert?

    Here's how it works 👇

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️