liveBook · Manning

MobX

As explained in Building User-Friendly DSLs

MobX is a JavaScript state-management library that tracks observable data and updates dependent computations or user-interface components when that data changes.

MobX makes a projectional editor reactive: observable AST and edit state changes automatically rerun dependent React projection components. section 5.0 section 5.1.3

A practical MobX integration separates three responsibilities:

  • Wrap components with observer so they rerender when the observable state they read changes. section 5.1.4
  • Wrap event handlers with action when they modify application state. section 5.1.4
  • Create observable edit-state objects before passing them to components such as TextValue. section 5.1.4

Making a text value editable

An observer-wrapped TextValue reads editState.inEdit. A click action sets that property to true; because the object is observable, the component switches from a span to an input. section 5.1.4

import React from "react" 
import { action } from "mobx"             #1
import { observer } from "mobx-react" 

export const TextValue = observer(({ editState }) => 
    editState.inEdit 
        ? <input type="text" 
            defaultValue={editState.value} 
            autoFocus={true} 
        /> 
        : <span className="value" 
            onClick={action((_) => {          #2
                editState.inEdit = true 
            })} 
        >{editState.value}</span> 
)

The listing combines observer, action, and conditional rendering in the TextValue component. section 5.1.4

How Building User-Friendly DSLs covers it

How deep it goes
Explains observer, action, and observable through component changes, but defers broader MobX details to another treatment.
Examples
Uses a TextValue component, observable editState, click actions, editable inputs, and styled name-value areas.
What it assumes
Assumes React projection components and an AST, while teaching MobX observability and state-changing actions in context.
What you can do after
Apply it via observer, action, and observable to build a React component that responds to editable state.
How it connects
Connects MobX with React components, ASTs, edit state, projection functions, and Transparent Functional Reactive Programming.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building User-Friendly DSLs. The section links point to the parts of the book it draws on.