Initially everything was working fine,I have a component something like. this
class A extends React.Component {
constructor(props) {
super(props);
this.childRef = null
}
componentDidMount() {
this.childRef = this.refs.b
// now I can call child function like this
this.childRef.calledByParent()
}
render(){
<B ref = "b"/>
}
}
In other file
class B extends React.Component {
calledByParent(){
console.log("i'm called")
}
render(){
<div> hello </div>
}
}
export default B
till here it was working fine but when I do something like this in class B
export default connect(mapStateToProps, mapDispatchToProps)(B)
It is not working. I have imported connect from react-redux
connect()
acceptsoption
as the forth parameter. In this option parameter you can set flagwithRef
to true. After this you can access functions to refs by usinggetWrappedInstance()
likeI had similar problem but I didn't want to make my APIs dependent on
getWrappedInstance()
calls. In fact some components in your class hierarchy may use connect() and access the store and some others are just stateless components that don't need that additional Redux layer.I have just written a small (maybe a bit hackish) method. Please note, it hasn't been fully tested yet so expect you may need to make some adjustments to get it working in your own scenario.
TypeScript (should be easy to convert to pure JavaScript syntax):
Use it by simply wrapping your
connect()
call withexposeWrappedMethods
. It will add all methods and properties from your own class (and subclasses) but will not overwrite already existing methods (i.e. methods from React.Component base class).Hope you (or someone else) find it useful.
/Lukasz
Might be a little late but another (better) solution than using refs is to only give control to specific functions of the component.