How to get a clicked HTML element in React?
Example
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props)
this.list_element = React.createRef()
this.state = {
items: [
{ text: 'Test1'},
{ text: 'Test2'},
{ text: 'Test3'},
{ text: 'Test4'}
]
}
}
doSomething(text, index) {
alert(text);
alert(index);
}
render() {
return (
<ol>
{this.state.items.map((item, index) => (
<li key={item.text} onClick={() => this.doSomething(item.text, index)}>
<span>{item.text}</span>
</li>
))}
</ol>
);
}
}
export default App;
Most Helpful This Week
How to pass data from child component to its parent in ReactJS?
React JS update Div content on click
Working with Forms, Inputs and onChange Events in ReactJs
React JS get Tag Name and Inner Text on Click
onMouseDown and onMouseUp Event handling in ReactJs
React Static Website with Material UI theme
How to pass an Argument to a Method used inside JSX expression?
How to show hide component on Click in React JS?
How to create Functional Component?
How to render raw HTML content in React JS?