0

I have an issue in my React.js app with the target id not being passed if a onClick event is attached on a div element.

This is how I add the component:

<MenuOption title="Users" onOptionClick={this.onOptionClick}/>

This is the jsx-part of my MenuOption component:

<div id={title} className="row menu-option" onClick={onOptionClick}>
   <p>{title}</p>
</div>

As you can see I'm simply assigning the prop title as the id and the onClick event.

Back in the parent component, implementation of the onClick method:

  onSidebarOptionClick(e) {
    console.log(e.target.id);
  }

This does not seem to work since it always logs undefined.

However, if I add the id and the onClick event to my p element instead...

<div className="row menu-option">
   <p id={title} onClick={onOptionClick}>{title}</p>
</div>

...it works just as expected, the correct id logs at every click.

So why is not the id passed if the click event is attached to a div?

I`m using ES6 and babel.

I should clarify that I'm using "dumb" components, declaring them like this:

const MenuOption = ({title, onOptionClick})

...which is why don't need to use {this.props.title} when using it.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
marsrover
  • 715
  • 11
  • 27

2 Answers2

0

Not sure as your Question missing constructor but try one of the following--

Method 1 (JSX):

<MenuOption title="Users" onOptionClick={this.onOptionClick.bind(this)}/>

Method 2 (es6):

   constructor(props) {
      super(props);
      this.onOptionClick = this.onOptionClick.bind(this);
   }

Method 3(es-next):

onSidebarOptionClick = (e) => {
    console.log(e.target.id);
 }
Fazal Rasel
  • 4,446
  • 2
  • 20
  • 31
0

As you're passing onOptionClick as a prop to <MenuOption/>, it should be declared as this.porops.onOptionClick.

<MenuOption/> should look like this

<div id={title} className="row menu-option" onClick={thi.props.onOptionClick}>
   <p>{title}</p>
</div>

Hope this helps!

Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70