node package manager

react-event-component

react event component

NPM version Build status License Code style

A very simple way to manage state in React apps.

Installation

$ npm install --save react-event-component

...or:

$ yarn add react-event-component

Usage

YourComponent.js

'use strict'
 
import React from 'react'
import {EventComponent} from 'react-event-component'
 
class YourComponent extends EventComponent {
  constructor (props) {
    super(props)
 
    this.state = {myValues: []}
  }
 
  render () {
    const {myValues} = this.state
 
    return (
      <div>
        There are {(myValues && myValues.length) || 'no'} values.
      </div>
    )
  }
}
 
export default YourComponent

ParentComponent.js

'use strict'
 
import 'babel-polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import {globalEventListener} from 'react-event-component'
 
import YourComponent from './YourComponent'
 
class ParentComponent extends React.Component {
  doStuff (value) {
    globalEventListener.emit('someEvent', state => {
      state.myValues = state.myValues.concat([value])
      return state
    })
  }
 
  render () {
    return (
      <div>
        <div>
          <YourComponent listenerId='someEvent' />
        </div>
 
        <div>
          <button onClick={this.doStuff}>
            Add Value
          </button>
        </div>
      </div>
    )
  }
}
 
ReactDOM.render(
  <ParentComponent />,
  document.getElementById('container')
)

The example above doesn't look too far away from what already in React, namely this.state and this.setState() but the point is that you can import {globalEventListener} and call globalEventListener.emit('yourEventName') from anywhere and the component will update.

Have a look in the example/ directory in this repo for a working example, just npm run bundle to transform ES2015/JSX into ES5 first.