How to access a redux component’s methods with createRef()
If you do a quick Google search for ‘share methods between react components’, it won’t take you long to stumble upon a stack overflow thread similar to this one which would recommend using refs. Refs in React are a way to access React elements or DOM nodes that have been created in the render method. Basically, refs give you access to all the typical DOM properties of a component (value, class, id, element…) but for a React component, it can give you access to its methods, which is pretty cool.
Typical ref usage example:
class Parent extends Component {
testMethod() {
return "Text from parent."
} render() {
return (
<div>Nothing important</div>
)
}
}class Child extends Component {
parentRef = React.createRef(); componentDidMount() {
console.log(this.parentRef.current.testMethod());
} render() {
return (
<div>
<Parent ref={this.parentRef} />
</div>
)
}
}
You should see “Text from parent.” in your console. View the code running in Codepen.
NOTE: Please bear in mind refs only work on class components and not function ones.