So we need to know if any of the inputs on the page are in focus and if any of them is focused then we just will not do anything to show or hide components.
Let's assume that our component has in the state some property which indicates that some input on the page is focused, let's call it isFocus
.
So, we need to collect all inputs on the page, iterate over them all and assign to each input the focus
and the blur
event handlers, so we will be able to know when to change the isFocus
property in the state.
First of all, we need to collect all of the inputs on the page, we do it with:
const inputs = document.getElementsByTagName('input')
.
Iterate over them all and assign the focus
and blur
event handlers:
for (let input of inputs) {
input.addEventListener('focus', () => this.setState({isFocus: true}));
input.addEventListener('blur', () => this.setState({isFocus: false}));
}
And finally, let's change the condition for the keypress
event:
document.addEventListener('keypress', e => {
if (!this.state.isFocus && e.key === "t") {
this.setState({opened: !this.state.opened});
}
});
Everything together will look like this:
componentDidMount() {
const inputs = document.getElementsByTagName('input');
for (let input of inputs) {
input.addEventListener('focus', () => this.setState({isFocus: true}));
input.addEventListener('blur', () => this.setState({isFocus: false}));
}
document.addEventListener('keypress', e => {
if (!this.state.isFocus && e.key === "t") {
this.setState({opened: !this.state.opened});
}
});
}
Hope this helps. Good luck.