JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Setting data attributes in React

Author:JIYIK Last Updated:2025/03/16 Views:

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>
  );
}

react set data attribute

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 datathe 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 removeAttributethe method.

el.removeAttribute('data-foo');

removeAttributeMethod 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 targetproperty 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 currentTargetproperty gives us access to the element the event listener is attached to.

If targetthe property refers to a descendant element in the scene, and we need to access the element the event listener is attached to, simply targetreplace 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 dataattributes.

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 .currentattributes 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 .currentsets the property of the ref object to the corresponding DOM node.

The ref attribute on currentthe 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 useEffectto 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.

Article URL:

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.

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.

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial