Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  6] [ 2]  / answers: 1 / hits: 64719  / 8 Years ago, sat, april 9, 2016, 12:00:00

How would I set the tabIndex attribute on a React component conditionally in the same way, say the disabled attribute is set?


I need to be able to set the value and/or remove the attribute all together.


First try was to make the entire attribute key and value a variable:


<div { tabIndex } ></div>

but the compiler complains.


Second thought was to:


const div;
if( condition ){
div = <div tabIndex="1"></div>
}else{
div = <div></div>
}

However, this is not desirable since my actual components have tons of attributes on them and I'd end up having large amounts of duplicate code.


My only other thought was to use a ref, then use jQuery to set the tabindex attributes, but I would rather not have to do it that way.


Any Ideas?


More From » reactjs

 Answers
29

You can do it using the attribute spread operator:



let props = condition ? {tabIndex: 1} : {};
let div = <div {...props} />

[#62636] Wednesday, April 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;