Is there a way to expose a function of a React component?
class MyComponent extends Component {
someFunction() {
// I'd like to expose this function
}
render() {
return(
<div>Hello World</div>
);
}
}
In the above example, I'd like to expose someFunction()
so that I can call it from the parent component.
In other words, I'm trying to call a function of a sub-component from the parent component.
Two questions:
While it is possible to call a function on a child component, I don't think it would be idiomatic.
If you want to change the way a component renders, you should alter its props and trigger a re-render.
Keeping the interface for a component exclusively through the props helps to better encapsulate the inner workings of the component.
For your specific example, I would rather have a visible
toggle that you alter and let the datePicker
component decide for itself what it wants to do with that property value.
Can I do this?
Yes, We can achieve that by using ref, assign ref to MyComponent when rendering inside parent component then use that ref to call the function.
How?
Check this snippet:
class Parent extends React.Component {
_callChildComponent(){
this.child.someFunction();
}
render() {
return(
<div>
<div onClick={() => this._callChildComponent()}>Call</div>
<MyComponent ref={el => this.child = el}/>
</div>
);
}
}
class MyComponent extends React.Component {
someFunction() {
console.log('hello');
}
render() {
return(
<div>Hello World</div>
);
}
}
ReactDOM.render(<Parent/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
But i will suggest you to pass a function from parent component to child component and use that function to pass data or for any other purpose instead of using ref.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With