Created
June 26, 2018 19:51
-
-
Save hovissimo/c9eef14b66095618112d22d8902acf24 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', []) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
React stunt: Hook into your child's callbacks.