Loic H
Loic H

Reputation: 348

Access to the parent key prop for all childrens events

I have a component that generate multiple row , inside those rows i have many input that i bound an onChange function. I need to access to the key of the current row for setState purpose. So i declare a data attribute for all my inputs data-id={key} ,

all this work perfectly but i think this is a high cost ressource that might be avoided ?

I was used to pass the key prop to the common parent (<tr>) here in Jquery and use the function parentsUntil(). but i don't think this is the goal here in React. Any suggestion how to avoid passing the key for all my inputs and access to the current key props on my parent (<tr>) ?

Upvotes: 1

Views: 76

Answers (2)

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

If looking at your code (which was embedded to question)

<tr key={key} id={key}>
    <td>
        <input name="quoteProducts.code" data-id={key} value={code} onChange={this._handleChange}/>
    </td>

There is this._handleChange handler. When it will be called, first argument will be event. It has currentTarget property which is DOM Element. DOM Element has parentNode property. In your code parentNode will be <td>. It in turn has also parentNode which will be <tr> you need. And you can access ll properties of <tr> you need.

Example:

_handleChange (event) {
    event.currentTarget.parentNode.parentNode.id // This is id of <tr>
}

id of any React component is easily accessible using previous example.

Upvotes: 1

xadm
xadm

Reputation: 8418

Real DOM elements/attributes can be reached in event handlers, by sth like:

handleChange(event) {
  const parentRow = event.target.parentElement.parentElement;  // input -> td -> tr
  const id = parentRow.attr("data-id");
  this.props.handleChange( {
    value: event.target.value, 
    rowId: id
  });
}

Of course, handler can (and should) be entirely defined (and binded) in parent and passed as prop.

Upvotes: 1

Related Questions