Skip to content

Instantly share code, notes, and snippets.

@hovissimo
Created June 26, 2018 19:51
Show Gist options
  • Save hovissimo/c9eef14b66095618112d22d8902acf24 to your computer and use it in GitHub Desktop.
Save hovissimo/c9eef14b66095618112d22d8902acf24 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export class AsyncModelField extends Component {
renderChild= () => {
// This function effectively hooks onChange on our children by cloning and merging new props.
// ASSUMPTION: this.props.children is actually just one child. You can map this across many though.
return React.cloneElement(this.props.children, {
onChange: function() {
// call ours
this.handleChange(...arguments)
// and if the child had one, call that too
if (this.props.children.props.onChange) {
this.props.children.props.onChange(...arguments)
}
}.bind(this),
})
}
handleChange(value, errors) {
console.log(value, errors)
}
render() {
return <div>
{ this.renderChild() }
</div>
}
}
import React from 'react'
import {shallow} from 'enzyme'
import chai, {expect} from 'chai'
import sinon from 'sinon'
import {AsyncModelField} from '../async_field'
describe.only('AsyncModelField component', function() {
it('should transparently bind its own handleChange to child\'s onChange', function() {
const spy = sinon.stub(AsyncModelField.prototype, 'handleChange')
const original = sinon.spy()
const wrapper = shallow(
<AsyncModelField><input onChange={original} /></AsyncModelField>
)
const instance = wrapper.instance()
wrapper.find('input').prop('onChange')('foo', [])
expect(spy).to.have.been.calledWith('foo', [])
expect(original).to.have.been.calledWith('foo', [])
})
})
@hovissimo
Copy link
Author

React stunt: Hook into your child's callbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment