'how to close react dropdown componet after out focus?

I've created a react dropdown component to show a list of data. this data get from server and I handle dropdown list show/hide with display property. I want to use this component in other components. I need that closed after click out of component in the parent.

export default class Dropdown extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        show: false,
        value: "",
        data: []
    };
    this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
    this.getData();
}
async getData() {
    const response = await fetch(this.props.url);
    const data = await response.json();
    this.setState({ data: data });
}
handleChange(event) {
    this.setState({ value: event.target.value });
}
render() {
    return (
        <div className={styles.container}>
            <input type="text" name="name"
                onClick={() => this.setState({ show: !this.state.show })}
                className={styles.bottonStyle}
                value={this.state.value}
                onChange={this.handleChange}
            />
            <div style={Object.assign({
                position: "absolute", backgroundColor: "#f9f9f9", minWidth: "350px", zIndex: "1"
            }, this.state.show ? { display: "block" } : { display: "none" })} >
                <div style={Object.assign({ backgroundColor: "lightgray" }, !this.state.showMounthList ? { display: "block" } : { display: "none" })} >

                    <table>
                        <tr style={{ backgroundColor: "orange" }}>
                            <th>Id</th>
                            <th>code</th>
                            <th>name</th>
                        </tr>
                        {
                            this.state.data.length > 0 ? (
                                this.state.data.map((item) => {
                                    return <tr>
                                        <td>{item.id}</td>
                                        <td>{item.code}</td>
                                        <td>{item.fullName}</td>
                                    </tr>
                                })
                            ) : null
                        }
                    </table>

                </div>
            </div >
        </div >);
}}


Solution 1:[1]

You can check for the focus of the element using below code :

First give your div id

var tableDiv = document.getElementById('id');

// check for focus
var isFocused = (document.activeElement === tableDiv);
this.setState({ show: isFocused })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1