Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic tabIndex attribute in JSX + React

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?

like image 699
Jesse Lee Avatar asked Apr 09 '16 21:04

Jesse Lee


People also ask

What is JSX element []?

What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

What attributes can I not write in JSX?

You can't write inlines styles in JSX. You have to reference an object in scope or pass an object that contains CSS properties, written as JS properties. JavaScript values can be injected into JSX using {} (e.g., test={text} and data-test={tested? 'test':'false'} ).

How do you write tabIndex in React?

In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attribute tabindex corresponds to the attribute tabIndex in React. The exception is aria-* and data-* attributes, which should be lowercased. For example, you can keep aria-label as aria-label .

How do I use htmlFor in React?

In class-based components, the htmlFor attribute is used to get the HTML for the given HTML elements. Creating React Application And Installing Module: Step 1: Create a React application using the following command. Step 2: After creating your project folder i.e. foldername, move to it using the following command.


2 Answers

You can do it using the attribute spread operator:

let props = condition ? {tabIndex: 1} : {};
let div = <div {...props} />
like image 87
Aaron Beall Avatar answered Oct 31 '22 05:10

Aaron Beall


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.

like image 22
2 revs, 2 users 90% Avatar answered Oct 31 '22 05:10

2 revs, 2 users 90%