0

I'm trying to call child component from parent component in reactjs using refs.but it throws error saying showModal() is not a function when I tried to call.

//app.js

 class app extends Component {
      constructor(props) {
         super(props);

         this.POPUP = React.createRef();
      }
      showModal(){
            this.POPUP.showModal(true);
      }
      render() {
         return (
             <React.Fragment>
                <span><a onClick={() => this.showModal()}>Show</a></span>

                <POPUP onRef={ref => (this.POPUP = ref)}></POPUP>
             </React.Fragment >
       )
     }
 }

popup.js

 class POPUP extends Component {
   showModal(show) {
         console.log('showmodal');

     }
   render() {
          console.log(this.props.showModalPopup);
       <React.Fragment>
             <Modal

                 position="center">
                 <div>
                     //code
                 </div>
             </Modal>
       </React.Fragment>
       )
     }
 }

Is there any alternative in nextjs.please help

Karthi
  • 3,019
  • 9
  • 36
  • 54

1 Answers1

3

https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs

First of all if you want to access that POPUP instance you should do

this.POPUP.current.showModal(true);

BTW Your showModal function needs to be bound to the child component if you intend to alter its state.

However, even this is doable - this is usually not the recommended way of doing React.

If you want the parent to decide if showModalPopup should be true, you probably should keep the state inside of your parent component:

 class App extends Component {
      constructor(props) {
         super(props);

         this.state = { showModalPopup: false };

         this.showModal = this.showModal.bind(this);
      }
      showModal(){
            this.setState({ showModalPopup: true });
      }
      render() {
         return (
             <React.Fragment>
                <span><a onClick={this.showModal}>Show</a></span>

                <POPUP show={this.state.showModalPopup}></POPUP>
             </React.Fragment >
       )
     }
 }
const POPUP = ({ show }) => (
    <Modal show={show} position="center">
      // your content.
    </Modal>
)

Yurui Zhang
  • 2,230
  • 16
  • 16