# react-robot
Table of Contents
The react-robot package provides the useMachine
hook for use with React.
import React from 'react';
import ReactDOM from 'react-dom';
import { createMachine, state, transition } from 'robot3';
import { useMachine } from 'react-robot';
const machine = createMachine({
off: state(
transition('toggle', 'on')
),
on: state(
transition('toggle', 'off')
)
});
function App() {
const [current, send] = useMachine(machine);
return (
<>
<div>State: {current.name}</div>
<button onClick={() => send('toggle')}>
Toggle
</button>
</>
);
}
ReactDOM.render(<App />, document.querySelector('#app'));
# Installation
Available as react-robot
on npm:
npm install react-robot --save
Or through Yarn:
yarn add react-robot
# API
useMachine(machine, initialContext)
Includes the arguments:
machine
: A Robot state machine.initialContext
: An object that will be passed to the context function.
Returns the following as an array:
[current, send, service]
current
: A state object with the properties:service
: A service like you normally get from interpret.
Normally only the current
and send
properties are needed to be used.
Here the state name
is logged, as well as data from the context.
const [current, send] = useMachine(machine);
const { userName } = current.context;
console.log('Current state:', current.name);
console.log('Username from context', userName);
The send
property is used to send events into the state machine:
const [current, send] = useMachine(machine);
return (
<button onClick={() => send('toggle')}>
Toggle
</button>
);