What is the best way to obtain the attribute value when a user clicks on a child element?

Is there a way to retrieve the value of the data-custom attribute when the red square is clicked without having to add the same attribute to nested elements? This can become cumbersome if there are multiple levels of nesting.

class Example extends React.Component {

  constructor(props){
    super(props)
    
    this.onClick = this.onClick.bind(this)
  }
  
  render(){
  
    return (
    
      <div className="large-box" data-custom="iExist" onClick={this.onClick}>
      
        <div className="box red"></div>
      
      </div>
    
    )
  
  }
  
  onClick(e){
  
    console.log(e.target.getAttribute('data-custom'))
  
  }

}

ReactDOM.render(<Example />,document.getElementById('app'))
.large-box {
  display:flex;
  width:200px;
  height:100px;
  border:1px solid black;

}

.box {
  margin:auto auto;
  width:40px;
  height:40px;

}

.red{background-color:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Answer №1

To keep things simple, just utilize event.currentTarget

Resource: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget


This helps in identifying the current target for the event as it moves through the DOM. It always points to the element where the event handler is attached, unlike event.target which points to the element on which the event took place.

class Sample extends React.Component {

  constructor(props){
    super(props)
    
    this.handleOnClick = this.handleOnClick.bind(this)
  }
  
  render(){
  
    return (
    
      <div className="big-container" data-custom="iExist" onClick={this.handleOnClick}>
      
        <div className="container red"></div>
      
      </div>
    
    )
  
  }
  
  handleOnClick(e){
    console.log(e.currentTarget.getAttribute('data-custom'))
  
  }

}

ReactDOM.render(<Sample />,document.getElementById('app'))
.big-container {
  display:flex;
  width:200px;
  height:100px;
  border:1px solid black;

}

.container {
  margin:auto auto;
  width:40px;
  height:40px;

}

.red{background-color:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Answer №2

To find the attribute data-custom, you can use the hasAttibute method. If the attribute is not present, you can retrieve it from the parentNode.

class Example extends React.Component {

  constructor(props){
    super(props)
    
    this.onClick = this.onClick.bind(this)
  }
  
  render(){
  
    return (
    
      <div className="large-box" data-custom="iExist" onClick={this.onClick}>
      
        <div className="box red"></div>
      
      </div>
    
    )
  
  }
  
  onClick(e){
  
    console.log(e.target.hasAttribute('data-custom')?e.target.getAttribute('data-custom'):e.target.parentNode.getAttribute('data-custom'))
  
  }

}

ReactDOM.render(<Example />,document.getElementById('app'))
.large-box {
  display:flex;
  width:200px;
  height:100px;
  border:1px solid black;

}

.box {
  margin:auto auto;
  width:40px;
  height:40px;

}

.red{background-color:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize Text Area's Font Based on Selected Option in Dropdown List

I'm currently working on an HTML file that includes a dropdown list and a text area. Here's the code snippet: <select id='ddlViewBy' name='ddlViewBy' onchange='applyfonttotextarea()'> <option value = ' ...

Trouble accessing onclick function

My dataSend AJAX function is not being called when I use the onclick event. I have checked in the Inspector of my browser and confirmed that the click handler is attached to it. However, when I set a breakpoint in the function using the Debugger, it never ...

When trying to load a php page2 into page1 via ajax, the Javascript code fails to execute

Currently, I am in the process of learning PHP and JavaScript. I have encountered a particular issue with a webpage setup. Let's say I have a page called page1 which consists of two input fields and a button labeled 'Go'. Upon clicking the & ...

Utilizing ReactJs refs to set focus on an input element

Exploring the use of refs in ReactJs to focus a textbox from a button click. Encountering the following error message: bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined Check out the Source Code below: class FocusTex ...

What is causing the issue of subdomains not functioning properly in express.js?

Currently, I am conducting some local experiments and have made changes to my hosts file. Here are the entries: 127.0.0.1 example.dev 127.0.0.1 www.example.dev 127.0.0.1 api.example.dev Below is the code I am using: var subdomain = req ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

The react app running on Docker is not functioning properly on localhost

Below is my Dockerfile configuration for the server: FROM node:18.13.0 WORKDIR /app COPY package*.json . RUN npm install COPY . . EXPOSE 8080 CMD [ "npm", "run", "start"] For the client, the Dockerfile looks like this: FR ...

Is it possible to update table cell content depending on selected option?

Displayed here is the select block: <form> <select id="select"> <option disabled selected value="choose"> CHOOSE </option> <option value="i2g" id="i ...

Is there a way to analyze and contrast information from two different maps?

I encountered a challenge while attempting to compare data from different tables in my database. I am currently still learning React and trying to implement a functionality where I can compare the data from recommendations and customizations, and display t ...

I am encountering an issue where the object I am sending with Next.js is appearing as undefined on the receiving page

When transferring data from my question screen to a result screen, I am using an object called footprintsData. Here is the code snippet for sending the data: const footprintsData = { carFootprint: roundedCarFootprint, electricityFootprint: roundedElect ...

Having an issue in Angular 2 where the correct function is not triggered when a button is placed within a selectable anchor

Within an anchor element, I have a button that triggers its own click listener for an editing popup module. The anchor itself has another click listener assigned to it. For example: <a (click)="onClick(myId)" class="list-group-item clearfix"> < ...

A guide to extracting iFrame information (specifically the referring URL) using JavaScript

Is there a way to retrieve the information from an iFrame (right-click on an iFrame in the browser -> This Frame -> View frame info)? I'm particularly interested in obtaining the referring URL. So far, I managed to retrieve the address using contentD ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...

Pass PHP date to JavaScript and increase its value

I'm looking to retrieve the server time with PHP and store it in a JavaScript variable. Once stored, I'd like it to continuously increment. Below is the code snippet: function initTime(date){ var today=new Date(date); var h=today.getHours(); v ...

Exploring MongoDB through User Interface Requests

As part of a project to develop a minimalist browser-based GUI for MongoDB, an interesting question has arisen. How can we accurately display the current state of the database and ensure it is continuously updated? Specifically, what methods can be utiliz ...

Develop a cross-platform application using webpack for both web browsers and Node.js

I'm currently developing my first module, and the code is almost identical for both browser and node.js versions. The only variance lies in the use of XmlHttpRequest for the browser and the http module for node.js. Here's a sample code snippet t ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

What is the best way to change the response URL in an AJAX function?

I have a function using ajax that redirects to the response from a specified URL upon success: document.getElementById("button1").addEventListener("click", function (e) { e.preventDefault(); $.ajax({ url: 'http://localhost:8080/someLo ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

Understanding how to handle prop types in a React application using Typescript

My current task involves using the react-google-maps library to integrate Google Maps API into my project. The documentation specifies a certain way to set up the maps component: const GoogleMapComponent: React.ComponentClass<{}> = compose( with ...