I have this simple component
class App extends React.Component {
a = () => null
b = () => null
c = () => null
render() {
return (<div>hey123</div>)
}
}
and this is my 2nd component with ref to the first one
class BApp extends React.Component {
setComponentRef = ref => {
console.log('ref', ref)
this.playerComponentRef = ref
}
render() {
return (
<div>
<App ref={this.setComponentRef} />
</div>)
}
}
in this case in the console.log I will receive all App component's functions (a, b, c)
but if I'll use Recompose.withState
on App
component I will not receive them anymore. see example here
https://codepen.io/anon/pen/qYjpoE?editors=1111
to see the working way swtich
<ModifyedApp ref={this.setComponentRef} />
to
<App ref={this.setComponentRef} />
what am I missing here ? why the use of Recompose HOC is removing the App
class component inner functions ?
thanks.
You can pass a function providerRef
to your component and then provide the App instance to it like
class BApp extends React.Component {
setComponentRef = ref => {
console.log('ref', ref)
this.playerComponentRef = ref
}
render() {
return (
<div>
<App providerRef={this.setComponentRef} />
</div>)
}
}
class App extends React.Component {
a = () => null
b = () => null
c = () => null
componentDidMount() {
this.props.providerRef(this);
}
render() {
return (<div>hey123</div>)
}
}
In case of Recompose, its an HOC and hence the ref will be applied on the HOC and not the inner component, some libraries provide a withRef
hook to access the innerComponent ref using this.playerComponentRef.getWrappedInstance()
, however I am not sure about its availability in recompose
.
HOC will create one new component outside children one. So if you are wrapping subcomponent in HOC and trying to receive ref of wrapped component you will get HOCs ref.
There is a workaround here - just pass a ref from the parent component to children in the hoc - just proxy the ref.