Create an update
function to pass messages to child components.
This idea is inspired by TEA (The Elm Architecture).
The library is originally designed to work with React components. But technically, it's applicable to any UI libraries/frameworks
npm install --save update-creator
Create a child component Child.js
const Child = ({ onClick, onSubmit, onChange }) => {
return (
<div>
<button onClick={onClick}>Cancel</button>
<input onChange={onChange} name="title" />
<button onClick={() => onSubmit({ title: 'foo bar' })}>Submit</button>
</div>
)
}
export default Child
Create constants for reusable messages Constants.js
export const MSG = {
CLICK: 'ON_CLICK',
SUBMIT: 'ON_SUBMIT',
CHANGE: 'ON_CHANGE'
}
Create the parent component
import React from 'react'
import updateCreator from 'update-creator'
import Child from './Child'
import { MSG } from './Constants'
const { CLICK, SUBMIT, CHANGE } = MSG
const parentMessages = [
CLICK,
SUBMIT,
CHANGE
]
class Parent extends React.Component {
update = updateCreator({
[CLICK]: () => {
console.log('on click')
},
[SUBMIT]: (values) => {
console.log('values', values)
},
[CHANGE]: (event) => {
console.log('current value', event.target.value)
}
}, parentMessages)
render() {
return (
<Child
onClick={this.update(CLICK)}
onSubmit={this.update(SUBMIT)}
onChange={this.update(CHANGE)}
/>
)
}
}
updateCreator(actions, messages = [])
-
actions
is a required object that contains event handlers, follow this pattern[message]: eventHandler
-
messages
is an optional array of messages. However, it's recommended to specify it so the library can detect whether theupdate
function covers all possibilities
MIT