Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A state machine abstraction for React

License

NotificationsYou must be signed in to change notification settings

MicheleBertoli/react-automata

Repository files navigation

npmBuild Statustested with jestcode style: prettier

React Automata

A state machine abstraction for React that provides declarative state management and automatic test generation.

Quick Start

Installation

yarn add react-automata

Usage

// App.jsimportReactfrom'react'import{Action,withStatechart}from'react-automata'exportconststatechart={initial:'a',states:{a:{on:{NEXT:'b',},onEntry:'sayHello',},b:{on:{NEXT:'a',},onEntry:'sayCiao',},},}exportclassAppextendsReact.Component{handleClick=()=>{this.props.transition('NEXT')}render(){return(<div><buttononClick={this.handleClick}>NEXT</button><Actionshow="sayHello">Hello, A</Action><Actionshow="sayCiao">Ciao, B</Action></div>)}}exportdefaultwithStatechart(statechart)(App)
// App.spec.jsimport{testStatechart}from'react-automata'import{App,statechart}from'./App'test('it works',()=>{testStatechart({ statechart},App)})
// App.spec.js.snapexports[`it works: a 1`]=`<div>  <button    onClick={[Function]}  >    NEXT  </button>  Hello, A</div>`;exports[`it works: b 1`]=`<div>  <button    onClick={[Function]}  >    NEXT  </button>  Ciao, B</div>`;

API

withStatechart(statechart[, options])(Component)

ThewithStatechart higher-order component takes anxstate configuration object or anxstate machine, someoptions and a component.It returns a new component with specialprops,action methods and additionallifecycle hooks.The initial machine state and the initial data can be passed to the resulting component through theinitialMachineState andinitialData props.

Options

OptionTypeDescription
channelstringThe key of the context on which to set the state.
devToolsboolTo connect the state machine to theRedux DevTools Extension.

Props

transition(event[, updater])

The method to change the state of the state machine.It takes an optional updater function that receives the previous data and returns a data change.The updater can also be an object, which gets merged into the current data.

handleClick=()=>{this.props.transition('FETCH')}

machineState

The current state of the state machine.

The use of this value is discouraged, as it couples the component and the state machine.

<buttononClick={this.handleClick}>{this.props.machineState==='idle' ?'Fetch' :'Retry'}</button>

Action methods

All the component's methods whose names match the names of the actions, are fired when the related transition happen.For example:

conststatechart={// ...fetching:{on:{SUCCESS:'success',ERROR:'error',},onEntry:'fetchGists',},// ...}classAppextendsReact.Component{// ...fetchGists(){fetch('https://api.github.com/users/gaearon/gists').then(response=>response.json()).then(gists=>this.props.transition('SUCCESS',{ gists})).catch(()=>this.props.transition('ERROR'))}// ...}

Lifecycle hooks

componentWillTransition(event)

The lifecycle method invoked when a transition is about to happen.It provides the event, and can be used to run side-effects.

componentWillTransition(event){if(event==='FETCH'){fetch('https://api.github.com/users/gaearon/gists').then(response=>response.json()).then(gists=>this.props.transition('SUCCESS',{ gists})).catch(()=>this.props.transition('ERROR'))}}

componentDidTransition(prevStateMachine, event)

The lifecycle method invoked when a transition has happened and the state is updated.It provides the previous state machine, and the event.The currentmachineState is available inthis.props.

componentDidTransition(prevStateMachine,event){Logger.log(event)}

<Action />

The component to define which parts of the tree should be rendered for a given action (or set of actions).

PropTypeDescription
hideoneOfType(string, arrayOf(string))The action(s) for which the children should be hidden.
showoneOfType(string, arrayOf(string))The action(s) for which the children should be shown. When bothshow andhide are defined, the children are shown from the firstshow match to the firsthide match.
channelstringThe key of the context from where to read the state.
childrennodeThe children to be rendered when the conditions match.
renderfuncTherender prop receives a bool (true when the conditions match) and it takes precedence over children.
onHidefuncThe function invoked when the component becomes invisible.
onShowfuncThe function invoked when the component becomes visible.
<Actionshow="showError">Oh, snap!</Action>
<Actionshow="showError"render={visible=>(visible ?<div>Oh, snap!</div> :null)}/>

<State />

The component to define which parts of the tree should be rendered for a given state (or set of states).

PropTypeDescription
valueoneOfType(string, arrayOf(string))The state(s) for which the children should be shown. It accepts the exact state, a glob expression or an array of states/expressions (e.g.value="idle",value="error.*" orvalue={['idle', 'error.*']).
channelstringThe key of the context from where to read the state.
childrennodeThe children to be rendered when the conditions match.
renderfuncTherender prop receives a bool (true when the conditions match) and it takes precedence over children.
onHidefuncThe function invoked when the component becomes invisible.
onShowfuncThe function invoked when the component becomes visible.
<Statevalue="error">Oh, snap!</State>
<Statevalue="error"render={visible=>(visible ?<div>Oh, snap!</div> :null)}/>

testStatechart({ statechart[, fixtures][, extendedState] }, Component)

The method to automagically generate tests given a statechart definition, and a component.It accepts an additionalfixtures option to describe the data to be injected into the component for a given transition, and anextendedState option to control the statechart's conditions - both are optional.

Please note that the component should be a base component not wrapped intowithStateChart (see#46).

Install "react-test-renderer" with a matching version to your React version.

yarn add --dev react-test-renderer
constfixtures={initialData:{gists:[],},fetching:{SUCCESS:{gists:[{id:'ID1',description:'GIST1',},{id:'ID2',description:'GIST2',},],},},}test('it works',()=>{testStatechart({ statechart, fixtures},App)})

Examples

Inspiration

Federico, for telling me "Hey, I think building UIs using state machines is the future".

David, for giving a very informative (and fun)talk about infinitely better UIs, and buildingxstate.

Ryan, forexperimenting with xstate and React - Ryan's approach to React has always been a source of inspiration.

Erik, for writing aboutstatecharts, and showing me how to keep UI and state machine decoupled.

About

A state machine abstraction for React

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors15


[8]ページ先頭

©2009-2025 Movatter.jp