Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing function of a React component

Tags:

reactjs

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:

  1. Can I do this? If so, how?
  2. This may be a more important question: Should I be doing this? I'm always mindful that something I may need now may be exposing an architectural flaw. So, I want to know if I should even be calling a sub-component's function from the parent component.
like image 260
Sam Avatar asked Mar 09 '23 04:03

Sam


2 Answers

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.

like image 193
christopher Avatar answered Mar 16 '23 05:03

christopher


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.

like image 28
Mayank Shukla Avatar answered Mar 16 '23 04:03

Mayank Shukla