How to access a redux component’s methods with createRef()

Richard Oliver Bray
Octopus Labs London
3 min readAug 4, 2019

--

Photo by bradley on Unsplash

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.

Fixing the problem with Refs…

--

--

Richard Oliver Bray
Octopus Labs London

Co-founder of orva.studio. Building digital products and teaching others to do the same. Saved by grace.