Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e.target is accessible, but e.target.value is not in React component

I'm having a strange issue with my React app where I can't get my deleteTime() function to work. I was going to try to remove an element from this.state.times by using e.target.value which would be the {key} for the <li> I want to remove. The value attribute is getting correctly added to the element, but I just can't access it. I know for a fact that the problem has to do with MaterializeCSS because if I change the element from an <i> to a <button> without the icons stuff, the code works.

There are basically two components, the main App which gives all the props to the RecentTimes component which just displays a list of times that are formatted like this: 00 : 00 . 00

Here is what the App component looks like (I removed all the irrelevant stuff):

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      times: []
    };
  }

  deleteTime(e) {
    console.log(e.target); // <i value="1" class="material-icons right" data-reactid=".0.0.2.0.0.2:$1.1">close</i>
    console.log(e.target.value); // undefined
  }

  render() {
    return (
      <RecentTimes
        times={this.state.times}
        deleteTime={this.deleteTime}
      />
    );
  }
}

I have no idea why e.target.value is undefined if e.target clearly has a value attribute.

And here is the component for the RecentTimes:

class RecentTimes extends React.Component {
  render() {
    let icons = 'material-icons right';

    let times = this.props.times.map((time, timeIndex) => {
      return (
        <li key={timeIndex}>
          {time}
          <i value={timeIndex} onClick={this.props.deleteTime} className={icons}>close</i>
        </li>
      );
    });

    return (
      <ul>{times}</ul>
    );
  }
}
like image 905
Saad Avatar asked Dec 11 '25 23:12

Saad


1 Answers

Use a data attribute

<i data-value={timeIndex} onClick={this.props.deleteTime} className={icons}>close</i>

and

e.target.getAttribute('data-value');

or if the browser supports dataset

e.target.dataset.value
like image 82
epascarello Avatar answered Dec 13 '25 12:12

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!