Reputation: 187
I want to use the same event handler for menu items when they are clicked.
In vanilla JavaScript the event handler 'this' value will point to the element and you can simply use this.id
, how is this done in React.
clickHandler2 and clickHandler3 I want to make into one event handler. The only thing different is the element clicked on.
The code is below:
import React from 'react';
import $ from 'jquery';
class MobileMenu extends React.Component {
constructor (props) {
super(props);
this.clickHandler1 = this.clickHandler1.bind(this);
this.clickHandler2 = this.clickHandler2.bind(this);
this.clickHandler3 = this.clickHandler3.bind(this);
this.state = {
current_item: 'nav_fave'
previous_item: null
};
}
clickHandler1 () {
this.toggleMenu();
}
clickHandler2 () {
// MenuPage.flip('fave');
this.toggleMenu();
this.toggleMarker($A.el('#nav_fave'));
}
clickHandler3 () {
// MenuPage.flip('splash');
this.toggleMenu();
this.toggleMarker($A.el('#nav_splash'));
}
toggleMarker (current_item) {
this.setState({
current_item: current_item
});
if ((this.previous_item !== undefined) && (this.previous_item !== current_item)) {
this.previous_item.style.borderBottom = '';
}
if (this.previous_item !== current_item) {
current_item.style.borderBottom = '3px solid #31baed';
}
this.previous_item = current_item;
}
toggleMenu () {
if (window.getComputedStyle($A.el('#top_menu_list'), null).display === 'block') {
$('#icon_bars').toggleClass('active');
$('#top_menu').slideToggle();
}
}
// ... snip
}
export default MobileMenu
Upvotes: 2
Views: 840
Reputation: 31024
You can pass the event parameter and use its target
property:
clickHandler2 (e) {
var id = e.target.id;
}
The this
in your case is the class
it self by the way.
Example:
class App extends React.Component{
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e){
const {id, value} = e.target;
console.log('id is - ' + id + ' and the value is: ' + value);
}
render(){
return(
<div>
<input id="input1" placeholder="type something" onChange={this.handleChange} />
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<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="root"></div>
Upvotes: 1