I am new to ReactJs. I am trying to avoid the keyboard tab focus event for <input>
, <a>
elements for specific div's. If div contains .text1
class name text1 div children elements should not be focussed.
In React I have done add/remove css className using props.
className={`${style.column5} ${ isActiveDiv ? style.column5Active : style.noTabindex }`}
I achieve this below output using jQuery. But, how do I do that in ReactJs?
$(document).ready(function() {
if ($(".text1").length){
$(".text1 input, .text1 a").attr("tabindex", "-1");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div class="text">
</div>
<div class="text1">
<input type="text" />
<a href="#">Anchor Tag</a>
</div>
<div class="text2">
<input type="text" />
</div>
<div class="text3">
<input type="text" />
</div>
</div>
So there's a couple ways you can handle this. The static way would be just pass in a tabIndex
property of -1 to those elements you don't want to focus:
<input type="text" tabIndex={-1} />
The dynamic way would be to find all elements that contain a class of text1
and then dynamically updating the tabIndex property of all their child elements. You can try something like this:
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const parentRef = React.createRef();
useEffect(() => {
//get children elements
const refChildren = Object.values(parentRef.current.children);
//find children with class of text1
const childrenWithText1Class = refChildren.filter(
child => child.className === "text1"
);
//find children's children to neglect
const childrensChildren = childrenWithText1Class.flatMap(child =>
Object.values(child.children)
);
const disableList = ["a", "input", "select", "textarea", "button"];
//neglect children
childrensChildren.forEach(elem => {
if (disableList.includes(elem.nodeName.toLowerCase())) {
elem.tabIndex = -1;
}
});
}, []);
return (
<div id="parent" ref={parentRef}>
<div class="text" />
<div class="text1">
<input type="text" />
<a href="#">Anchor Tag</a>
<select />
<textarea />
<audio controls />
<button>Check</button>
</div>
<div class="text2">
<input type="text" />
</div>
<div class="text3">
<input type="text" />
</div>
</div>
);
}
See working sandbox: https://codesandbox.io/s/elastic-sara-blp9q
You can test it by clicking into the div
(background) with the text1
class and try tabbing. You'll see that you actually end up skipping over to the next block.