Setting data attributes in React
To set data attributes for an element in React , set the attribute directly on the element, e.g. <button data-test-id="my-btn">
or use setAttribute()
the getData method, e.g. el.setAttribute('data-foo', 'bar')
We can access the element on the event object or use ref
.
export default function App() {
const handleClick = event => {
console.log(event.target.dataset);
// 👇️ "my-btn"
console.log(event.target.getAttribute('data-test-id'));
// 👇️ set attribute
event.target.setAttribute('data-foo', 'bar');
console.log(event.target.getAttribute('data-foo')); // 👉️ bar
event.target.setAttribute('data-foo', 'baz');
console.log(event.target.getAttribute('data-foo')); // 👉️ baz
};
return (
<div>
{/* 👇️ set data-test-id attribute */}
<button onClick={handleClick} data-test-id="my-btn">
Click
</button>
</div>
);
}
If we need to access an element via ref instead of the event object, scroll down to the next section.
We can set attributes data-*
directly on an element using the syntax .data
<button onClick={handleClick} data-test-id="my-btn">
Click
</button>
Note that we don't use camelCase for custom data-*
properties.
This example shows how to use the method in an event setAttribute()
to programmatically set or update data
the property.
event.target.setAttribute('data-foo', 'bar');
This method requires the following 2 parameters:
- name - the name of the property to be set.
- value - The value to be assigned to the property.
If the attribute already exists on the element, updates the value, otherwise adds a new attribute with the specified name and value.
If you need to remove an attribute from an element, you may use removeAttribute
the method.
el.removeAttribute('data-foo');
removeAttribute
Method removes the attribute with the specified name from an element.
If the attribute does not exist on the element, the method returns without throwing an error.
The event's target
property gives us a reference to the element (possibly a descendant) that triggered the event.
const handleClick = event => {
console.log(event.target.dataset);
// 👇️ "my-btn"
console.log(event.target.getAttribute('data-test-id'));
// 👇️ set attribute
event.target.setAttribute('data-foo', 'bar');
console.log(event.target.getAttribute('data-foo')); // 👉️ bar
event.target.setAttribute('data-foo', 'baz');
console.log(event.target.getAttribute('data-foo')); // 👉️ baz
};
The event's currentTarget
property gives us access to the element the event listener is attached to.
If target
the property refers to a descendant element in the scene, and we need to access the element the event listener is attached to, simply target
replace with currentTarget
.
const handleClick = event => {
console.log(event.currentTarget.dataset);
// 👇️ "my-btn"
console.log(event.currentTarget.getAttribute('data-test-id'));
// 👇️ set attribute
event.currentTarget.setAttribute('data-foo', 'bar');
console.log(event.currentTarget.getAttribute('data-foo')); // 👉️ bar
event.currentTarget.setAttribute('data-foo', 'baz');
console.log(event.currentTarget.getAttribute('data-foo')); // 👉️ baz
};
Alternatively, we can use ref to access a DOM element to set its data
attributes.
import {useRef} from 'react';
export default function App() {
const ref = useRef(null);
const handleClick = () => {
console.log(ref.current.dataset);
// 👇️ "my-btn"
console.log(ref.current.getAttribute('data-test-id'));
// 👇️ set attribute
ref.current.setAttribute('data-foo', 'bar');
console.log(ref.current.getAttribute('data-foo')); // 👉️ bar
ref.current.setAttribute('data-foo', 'baz');
console.log(ref.current.getAttribute('data-foo')); // 👉️ baz
};
return (
<div>
<button ref={ref} onClick={handleClick} data-test-id="my-btn">
Click
</button>
</div>
);
}
This code example achieves the same result, but we use a ref to access the DOM element.
useRef()
The hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current
attributes are initialized to the passed argument.
请注意
, we have to access the current property of the ref object to access the button element to which we set the ref attribute.
When we pass a ref prop to an element, for example <button ref={myRef} />
, React .current
sets the property of the ref object to the corresponding DOM node.
The ref attribute on current
the button element gives us access to the button element, so we can ref.current.setAttribute('data-foo', 'bar')
set the data attribute on the element using .
Make sure useEffect
to access the ref in a hook or when an event occurs, because if we try to access the ref right away, it may not have been set yet, or the element may not be in the DOM yet.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap