Dynamic tabIndex attribute in JSX + React
I believe there is a simpler way (than Aaron's suggestion).
React removes an attribute from a JSX element if that attribute's value is null or undefined. I'd need this to be confirmed by someone who knows for sure.
Therefore you can use something like this:
let t1 = condition ? 1 : null;
let div = <div tabIndex={t1}>...</div>;
The tabIndex
attribute will be removed if t1
is null.
For example, we have three attributes, tabIndex, class and id.
let tabIndex;
let id;
let className = "tab";
let props = {
tabIndex,
className,
id,
}
let div = <div {...props} />
undefined/null value props will not add in div, so the render result is
<div class="tab" />
You can do it using the attribute spread operator:
let props = condition ? {tabIndex: 1} : {};
let div = <div {...props} />