{"id":21031157,"url":"https://github.com/michelebertoli/react-automata","last_synced_at":"2025-05-15T04:06:25.066Z","repository":{"id":40003143,"uuid":"109186685","full_name":"MicheleBertoli/react-automata","owner":"MicheleBertoli","description":"A state machine abstraction for React","archived":false,"fork":false,"pushed_at":"2019-01-23T15:44:06.000Z","size":465,"stargazers_count":1335,"open_issues_count":14,"forks_count":46,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-03-30T23:06:08.247Z","etag":null,"topics":["reactjs","state-machine","statecharts","xstate"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MicheleBertoli.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-01T21:38:39.000Z","updated_at":"2025-02-11T15:49:50.000Z","dependencies_parsed_at":"2022-06-26T06:01:11.746Z","dependency_job_id":null,"html_url":"https://github.com/MicheleBertoli/react-automata","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MicheleBertoli%2Freact-automata","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MicheleBertoli%2Freact-automata/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MicheleBertoli%2Freact-automata/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MicheleBertoli%2Freact-automata/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MicheleBertoli","download_url":"https://codeload.github.com/MicheleBertoli/react-automata/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247569113,"owners_count":20959760,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["reactjs","state-machine","statecharts","xstate"],"created_at":"2024-11-19T12:25:03.562Z","updated_at":"2025-04-07T00:08:31.239Z","avatar_url":"https://github.com/MicheleBertoli.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![npm](https://img.shields.io/npm/v/react-automata.svg)](https://www.npmjs.com/package/react-automata)\n[![Build Status](https://travis-ci.org/MicheleBertoli/react-automata.svg?branch=master)](https://travis-ci.org/MicheleBertoli/react-automata)\n[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest)\n[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)\n\n# React Automata\n\nA state machine abstraction for React that provides declarative state management and automatic test generation.\n\n# Quick Start\n\n## Installation\n\n\u003e `react` and `react-test-renderer` are peer dependencies.\n\n```sh\nyarn add react-automata\n```\n\n## Usage\n\n```js\n// App.js\n\nimport React from 'react'\nimport { Action, withStateMachine } from 'react-automata'\n\nconst statechart = {\n  initial: 'a',\n  states: {\n    a: {\n      on: {\n        NEXT: 'b',\n      },\n      onEntry: 'sayHello',\n    },\n    b: {\n      on: {\n        NEXT: 'a',\n      },\n      onEntry: 'sayCiao',\n    },\n  },\n}\n\nclass App extends React.Component {\n  handleClick = () =\u003e {\n    this.props.transition('NEXT')\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cbutton onClick={this.handleClick}\u003eNEXT\u003c/button\u003e\n        \u003cAction is=\"sayHello\"\u003eHello, A\u003c/Action\u003e\n        \u003cAction is=\"sayCiao\"\u003eCiao, B\u003c/Action\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nexport default withStateMachine(statechart)(App)\n```\n\n```js\n// App.spec.js\n\nimport { testStateMachine } from 'react-automata'\nimport App from './App'\n\ntest('it works', () =\u003e {\n  testStateMachine(App)\n})\n```\n\n```js\n// App.spec.js.snap\n\nexports[`it works: a 1`] = `\n\u003cdiv\u003e\n  \u003cbutton\n    onClick={[Function]}\n  \u003e\n    NEXT\n  \u003c/button\u003e\n  Hello, A\n\u003c/div\u003e\n`;\n\nexports[`it works: b 1`] = `\n\u003cdiv\u003e\n  \u003cbutton\n    onClick={[Function]}\n  \u003e\n    NEXT\n  \u003c/button\u003e\n  Ciao, B\n\u003c/div\u003e\n`;\n```\n\n# API\n\n## withStateMachine(statechart[, options])(Component)\n\nThe `withStateMachine` higher-order component accepts an [xstate configuration object](http://davidkpiano.github.io/xstate/docs/#/api/config) or an [xstate machine](http://davidkpiano.github.io/xstate/docs/#/api/machine), some [options](#options) and a component.\nIt returns a new component with special [props](#props), [action and activity methods](#action-and-activity-methods) and additional [lifecycle hooks](#lifecycle-hooks).\nThe initial machine state and the initial data can be passed to the resulting component through the `initialMachineState` and `initialData` props.\n\n### Options\n\n| Option | Type | Description |\n| ------ | ---- | ----------- |\n| channel | string | The key of the context on which to set the state. |\n| devTools | bool | To connect the state machine to the [Redux DevTools Extension](https://github.com/zalmoxisus/redux-devtools-extension). |\n\n### Props\n\n#### transition(event[, updater])\n\nThe method to change the state of the state machine.\nIt takes an optional updater function that receives the previous data and returns a data change.\nThe updater can also be an object, which gets merged into the current data.\n\n```js\nhandleClick = () =\u003e {\n  this.props.transition('FETCH')\n}\n```\n\n#### machineState\n\nThe current state of the state machine.\n\n\u003e It's not recommended to use this value because it couples the component and the state machine.\n\n```js\n\u003cbutton onClick={this.handleClick}\u003e\n  {this.props.machineState === 'idle' ? 'Fetch' : 'Retry'}\n\u003c/button\u003e\n```\n\n### Action and Activity methods\n\nAll the component's methods whose names match the names of actions and activities, are fired when the related transition happen.\nActions receive the state and the event as arguments. Activities receive a boolean that is true when the activity should start, and false otherwise.\n\nFor example:\n\n```js\nconst statechart = {\n  // ...\n  fetching: {\n    on: {\n      SUCCESS: 'success',\n      ERROR: 'error',\n    },\n    onEntry: 'fetchGists',\n  },\n  // ...\n}\n\nclass App extends React.Component {\n  // ...\n  fetchGists() {\n    fetch('https://api.github.com/users/gaearon/gists')\n      .then(response =\u003e response.json())\n      .then(gists =\u003e this.props.transition('SUCCESS', { gists }))\n      .catch(() =\u003e this.props.transition('ERROR'))\n  }\n  // ...\n}\n\n```\n\n### Lifecycle hooks\n\n#### componentWillTransition(event)\n\nThe lifecycle method invoked when the [transition function](#transitionevent-updater) has been called.\nIt provides the event, and can be used to run side-effects.\n\n```js\ncomponentWillTransition(event) {\n  if (event === 'FETCH') {\n    fetch('https://api.github.com/users/gaearon/gists')\n      .then(response =\u003e response.json())\n      .then(gists =\u003e this.props.transition('SUCCESS', { gists }))\n      .catch(() =\u003e this.props.transition('ERROR'))\n  }\n}\n```\n\n#### componentDidTransition(prevMachineState, event)\n\nThe lifecycle method invoked when a transition has happened and the state is updated.\nIt provides the previous state machine, and the event.\nThe current `machineState` is available in `this.props`.\n\n```js\ncomponentDidTransition(prevMachineState, event) {\n  Logger.log(event)\n}\n```\n\n## \u0026lt;Action /\u0026gt;\n\nThe component to define which parts of the tree should be rendered for a given action (or set of actions).\n\n| Prop | Type | Description |\n| ---- | ---- | ----------- |\n| is | oneOfType(string, arrayOf(string)) | The action(s) for which the children should be shown. It accepts the exact value, a glob expression or an array of values/expressions (e.g. `is=\"fetch\"`, `is=\"show*\"` or `is={['fetch', 'show*']`). |\n| channel | string | The key of the context from where to read the state. |\n| children | node | The children to be rendered when the conditions match. |\n| render | func | The [render prop](https://reactjs.org/docs/render-props.html) receives a bool (true when the conditions match) and it takes precedence over children. |\n| onHide | func | The function invoked when the component becomes invisible. |\n| onShow | func | The function invoked when the component becomes visible. |\n\n```js\n\u003cAction is=\"showError\"\u003eOh, snap!\u003c/Action\u003e\n```\n\n```js\n\u003cAction\n  is=\"showError\"\n  render={visible =\u003e (visible ? \u003cdiv\u003eOh, snap!\u003c/div\u003e : null)}\n/\u003e\n```\n\n## \u0026lt;State /\u0026gt;\n\nThe component to define which parts of the tree should be rendered for a given state (or set of states).\n\n| Prop | Type | Description |\n| ---- | ---- | ----------- |\n| is | oneOfType(string, arrayOf(string)) | The state(s) for which the children should be shown. It accepts the exact value, a glob expression or an array of values/expressions (e.g. `is=\"idle\"`, `is=\"error.*\"` or `is={['idle', 'error.*']`). |\n| channel | string | The key of the context from where to read the state. |\n| children | node | The children to be rendered when the conditions match. |\n| render | func | The [render prop](https://reactjs.org/docs/render-props.html) receives a bool (true when the conditions match) and it takes precedence over children. |\n| onHide | func | The function invoked when the component becomes invisible. |\n| onShow | func | The function invoked when the component becomes visible. |\n\n```js\n\u003cState is=\"error\"\u003eOh, snap!\u003c/State\u003e\n```\n\n```js\n\u003cState\n  is=\"error\"\n  render={visible =\u003e (visible ? \u003cdiv\u003eOh, snap!\u003c/div\u003e : null)}\n/\u003e\n```\n\n## testStateMachine(Component[, { fixtures, extendedState }])\n\nThe method to automagically generate tests given a component wrapped into `withStateMachine`.\nIt accepts an additional `fixtures` option to describe the data to be injected into the component for a given transition, and an `extendedState` option to control the statechart's conditions - both are optional.\n\n```js\nconst fixtures = {\n  initialData: {\n    gists: [],\n  },\n  fetching: {\n    SUCCESS: {\n      gists: [\n        {\n          id: 'ID1',\n          description: 'GIST1',\n        },\n        {\n          id: 'ID2',\n          description: 'GIST2',\n        },\n      ],\n    },\n  },\n}\n\ntest('it works', () =\u003e {\n  testStateMachine(App, { fixtures })\n})\n```\n\n# Examples\n\n- [Ian Horrocks' Calculator](https://codesandbox.io/s/n5vvn4jrpm)\n\n- [React Flickr Gallery App](https://codesandbox.io/s/z20llylz9l)\n\n- [Playground](./playground)\n\n- [React Loads](https://github.com/jxom/react-loads)\n\n- [Packing List](https://codesandbox.io/s/github/GantMan/ReactStateMuseum/tree/master/React/react-automata) ([React Native](https://github.com/GantMan/ReactStateMuseum/tree/master/ReactNative/ReactAutomata))\n\n# Frequently Asked Questions\n\nYou might find the answer to your question [here](FAQ.md).\n\n# Upgrades\n\nThe upgrade process is documented [here](UPGRADING.md).\n\n# Inspiration\n\n[Federico](https://twitter.com/gandellinux), for telling me \"Hey, I think building UIs using state machines is the future\".\n\n[David](https://twitter.com/DavidKPiano), for giving an awesome [talk](https://www.youtube.com/watch?v=VU1NKX6Qkxc) about infinitely better UIs, and building [xstate](https://github.com/davidkpiano/xstate).\n\n[Ryan](https://twitter.com/ryanflorence), for [experimenting](https://www.youtube.com/watch?v=WbhpQXH7XMw) with xstate and React - Ryan's approach to React has always been a source of inspiration to me.\n\n[Erik](https://twitter.com/mogsie), for writing about [statecharts](https://statecharts.github.io/), and showing me how to keep UI and state machine decoupled.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichelebertoli%2Freact-automata","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichelebertoli%2Freact-automata","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichelebertoli%2Freact-automata/lists"}