ts-react-struct

1.0.0 • Public • Published

ts-react-struct

npm version NPM downloads Build Status

ts-react-struct is a TypeScript package for using React and immutable.js with type-safe cursors and a central event system. The emphasis here is on type-safety.

You'll usually want to combine this with ts-immutable-struct.

Getting started

Install the package:

npm install --save ts-immutable-struct ts-react-struct

Example usage:

import * as React from 'react'
import {ChangeEvent} from 'react'
import * as ReactDom from 'react-dom'
import {Struct, LeafRef} from 'ts-immutable-struct'
import {Component} from 'ts-react-struct'
 
interface Props extends React.HTMLProps<HTMLInputElement> {
  valueRef: LeafRef<string>,
}
 
class Input extends Component<Props> {
  onChange = (event: ChangeEvent<HTMLInputElement>) => {
    this.props.valueRef.val(event.target.value,event)
  }
 
  render() {
    let props: Props = Object.assign({}, this.props)
    delete props.valueRef
    return <input {...props} value={this.props.valueRef.deref()} onChange={this.onChange} />
  }
}
 
let data = Struct({
  value: 'ahoy',
})
 
function render() {
  return ReactDom.render(<Input valueRef={data.get('value')} />, document.getElementById('content'))
}
render()
 
data.observe((event, oldVal, newVal) => {
  render()
})

Now, the state is always in sync with the DOM:

data.get('value').deref()
// => "ahoy"
 
data.get('value').val('hola')
// => Input gets rerendered as <input value="hola" />
 
// <= user types "hey" into input field
data.get('value').deref() // => "hey"

Package Sidebar

Install

npm i ts-react-struct

Weekly Downloads

2

Version

1.0.0

License

MIT

Last publish

Collaborators

  • wkornewald