Ad Code

Ticker

6/recent/ticker-posts

Passing Arguments to Event Handlers in React

React event handler work on Html elements or custom components created in react. In this section see what is the structure and how to access extra data related to elements in react event handlers.

Passing Arguments to Event Handlers in React

Simple Click event:

class RandomFunction extends React.Component {
  ClickHandler = () => {
    alert("button clicked");
  }
  render() {
    return <button onclick="{this.ClickHandler}">Press to hear your message.</button>;
  }
}

the above example shows a simple click event, then click on the button then the click handler defined an alert box shows.

Click with element argument


class RandomFunction extends React.Component {
  ClickHandler = (e) => {
    alert(e.target.textContent);
  }
  render() {
    return <button onclick="{e=>this.ClickHandler(e)}">Press to hear your message.</button>;
  }
}

the above example shows click event element text read and shows in the alert box when click, and is this example also read element attribute and another query like parent and child element data access.

Click with element argument and passing an extra argument


class RandomFunction extends React.Component {
  ClickHandler = (e, text) => {
    alert(text);
  }
  render() {
    return <button onclick="{e=>this.ClickHandler(e, "Welcome to react click event handler.")}">Press to hear your message.</button>;
  }
}

in this example passing an extra argument in click handler to perform their actions inside function and defined logic.

Post a Comment

0 Comments

Ad Code