zanhtet
zanhtet

Reputation: 2050

Add callback function to parent component from child component

I got parent component and child component(tooltip component). In child component's componentdidmount, I want to add callback function to parent component to close child component. How can I add callback function to parent component from child component.

export default class Parent extends React.Component {
    constructor(){
        super();
    }

    render() {
        <div>
             sdf adfa sfdsf
             saf
             a sfdsaf sfsf safdsa
             asdf safdsaf safdsafasdf
             asdf safdsafdsafsadf
             asdf asfsadfdsafdsaf
             ..............
            <Child />
        </div>
    }
}

export default class Child extends React.Component {
    constructor(){
        super();
        this.state = {
            IsShownTooltip: false
        }
    }

    componentDidMount = () => {
        //want to add Parent div on click here to close popup with setstate
    }

    onClick = () => {
        this.setState({
            IsShownTooltip: true
        });
    }

    render() {
        <div onClick={this.onClick}>
            {this.state.IsShownTooltip && 
                <div>tooooooooooooooooltip text hererrrrrrrrrr</div>
            }
        </div>
    }
}

Upvotes: 0

Views: 582

Answers (1)

Venkatesh Somu
Venkatesh Somu

Reputation: 5020

You can do the show/hide toggle functionality in Parent component like this.

1.Parent.js

import React, { Component } from 'react';
import Child from './Child';

export default class Parent extends Component {
  constructor(props){
    super(props);
    this.state = {
        IsShownTooltip: false
    }
}

onClickToggle = () => {
    this.setState({
        IsShownTooltip: !this.state.IsShownTooltip,
    })
}
render() {
    return(
    <div>
         parent
         ..............
         <button onClick={() => this.onClickToggle()}>click</button>
        <Child IsShownTooltip={this.state.IsShownTooltip} onClickChild={() => this.onClickToggle()} />
    </div>
    )
  }
}
  1. Child.js

    import React, { Component } from 'react';
    
    export default class Child extends Component {
    
    render() {
      return(
        <div onClick={this.onClick}>
            <button onClick={() => this.props.onClickChild()}>click</button>
            {this.props.IsShownTooltip && 
                <div>tooooooooooooooooltip text hererrrrrrrrrr</div>
            }
        </div>
     )
    }}
    

    The code can be improved a lot, just for the output of your provided example, I wrote this. Hope this will be helpful to you :)

Upvotes: 1

Related Questions