Check for classes when clicked (React)

I want to check if a specific element has the specified class when clicked. I know that you can bind a click handler that passes to the e.targethandler. My thinking was to get e.target.classList.indexOf(this.myClass) > -1to find out if he has a class, but I get the following error.

e.target.classList.indexOf is not a function

I guess this is because it classListis an object that looks like an array, not an actual array. Is there an easier way to get a list of classes from a clicked element in React without doing all the “slice call” magic?

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.myClass = 'my-class';
    }

    handleClick(e) {
        // check if e.target class has this.myClass
        if (/* logic */) {
            // perform action
        }
    }

    render() {
        return <div onClick={this.handleClick.bind(this)} className={this.myClass + ' other-class'}>
            <div>My Component</div>
        </div>
    }

}

How can I get an array of classes from a "target" click element in a React event system?

+4
2

Element.classList contains(), :

e.target.classList.contains(this.myClass)

Docs


, this , , , , , . bind().

+6

.contains .,

contains( String ) , .

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myClass = 'my-class';
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    console.log(e.currentTarget.classList.contains(this.myClass))
  }

  render() {
    return <div 
      className={this.myClass + ' other-class'} 
      onClick={this.handleClick}
    >
      <div>My Component</div>
    </div>
  }
}


ReactDOM.render(
  <MyComponent name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
Hide result
+4

Source: https://habr.com/ru/post/1650351/


All Articles