Reputation: 157
I am new to ReactJS and badly stuck at something.
I have a custom modal that pops up on click of a button. This modal contains 2 other buttons. Problem occurs when I start pressing tab button. :( The focus moves behind the modal screen and user is able to interact with the application which is a strict no no!
I can't use React modal for this one.
Is there a way to make the focus stick to the modal div on top using ReactJS/Javascript. So far I have tried the following but it doesn't seem to work properly.
Please have a look. Any help will be highly appreciated.
_focusRestrict() {
document.addEventListener('keydown', event => {
if (this.state.resetLifePlanner) {
//alert('Called');
event.stopPropagation();
const key = (event.keyCode ? event.keyCode : event.which);
switch (key) {
case 9:
if (document.activeElement.id === 'confirmButton') {
console.log('Called if:: move focus to cancelButton');
this.cancelButton.focus();
//React.findDOMNode(this.refs.cancelButton).focus();
//document.getElementById('cancelButton').focus();
}
else if (document.activeElement.id === 'cancelButton') {
console.log('Called else:: move focus to confirmButton');
this.confirmButton.focus();
//React.findDOMNode(this.refs.confirmButton).focus();
//document.getElementById('confirmButton').focus();
}
}
}
}, true);
}
componentDidMount() {
this._focusRestrict();
}
Is there a ReactJS event handling way of doing it?
Also, is there a way to bind the event to the div?
Upvotes: 0
Views: 878
Reputation: 157
The answer above is right. But we also need to add
// This is needed to properly add and remove the keydown event listener
this._restrictFocus = _.bind(this._restrictFocus, this);
in the constructor of the react component. Otherwise it doesn't seem to work.
Hope this helps.
Upvotes: 0
Reputation: 6110
After event.stopPropagation();
, just add event.preventDefault();
Don't forget to remove your listener when unmounting your modal component. You will have to place the current anonymous fonction in a named fonction.
export default class ArtistList extends Component {
// ...
componentDidMount() {
document.addEventListener('keydown', handleKeydown, true);
}
componentWillunmount() {
document.removeEventListener('keydown', handleKeydown);
}
}
function handleKeydown(e) {
if (this.state.resetLifePlanner) {
//alert('Called');
event.stopPropagation();
event.preventDefault();
const key = (event.keyCode ? event.keyCode : event.which);
switch (key) {
case 9:
if (document.activeElement.id === 'confirmButton') {
console.log('Called if:: move focus to cancelButton');
this.cancelButton.focus();
//React.findDOMNode(this.refs.cancelButton).focus();
//document.getElementById('cancelButton').focus();
}
else if (document.activeElement.id === 'cancelButton') {
console.log('Called else:: move focus to confirmButton');
this.confirmButton.focus();
//React.findDOMNode(this.refs.confirmButton).focus();
//document.getElementById('confirmButton').focus();
}
}
}
}
Upvotes: 1