Categories
React Answers

How to retrieve dynamic child key upon emission of an event with React?

Spread the love

Sometimes, we want to retrieve dynamic child key upon emission of an event with React.

In this article, we’ll look at how to retrieve dynamic child key upon emission of an event with React.

How to retrieve dynamic child key upon emission of an event with React?

To retrieve dynamic child key upon emission of an event with React, we can store the key as a data- attribute.

Then we can get the data- attribute value from the dataset property.

For instance, we write:

import React from "react";

const ChildComponent = ({ changeCallback, dataKey }) => {
  return (
    <div>
      <input type="text" onChange={changeCallback} data-key={dataKey} />
    </div>
  );
};

export default function App() {
  const changeCallback = (evt) => {
    console.log(evt.target.dataset.key);
  };

  return (
    <div>
      <ChildComponent changeCallback={changeCallback} dataKey="abc" />
    </div>
  );
}

We create the ChildComponent component that renders an input element with the data-key attribute set to the dataKey prop’s value.

Also, set set the onChange prop of the input to changeCallback.

Next, we define changeCallback in App that gets the data-key attribute value with evt.target.dataset.key.

We render ChildComponent with changeCallback and dataKey set so that when we type in the input, we see the data-key attribute value logged.

Cobnclusion

To retrieve dynamic child key upon emission of an event with React, we can store the key as a data- attribute.

Then we can get the data- attribute value from the dataset property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *