V
V
Vladimir2018-08-28 12:48:59
React
Vladimir, 2018-08-28 12:48:59

How to access data attributes in React?

I 'm trying to
bind
date attributes to a
custom component, throwing them inside this component how to bind your attributes to the component in order to reach them through event.target ?
I do this to avoid such event handlers
https://stackblitz.com/edit/react-khcwbu?file=index.js

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-28
@Casufi

const MyInput = props => {
  const { onChange } = this.props;
  const id = this.props['data-id'];
  const name = this.props['data-name'];
  
  return <input onChange={onChange} data-id={id} data-name={name} />;
};

or:
In handler:
onChange = e => {
  const { id, name } = e.target.dataset;
  // do something with id and name
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question