Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

span does not firing OnClick inside list react child component

I have 2 components when the parent trigger by OnClick the child which has span element doesn't fire OnClick at all. I try it when the parent is button and it works perfectly but when the parent is list it doesn't trigger the child.

class Menu extends Component {
 handleItemClick=(e)=>{
     // whatever ..
 }
 render(){
  return(
   <ul>
     {
       items.map((item, i)=>(
            <li key={i}
                id={i}
                onClick={this.handleItemClick}>
                <Child />
                {item}
            </li>
        ))
     }
   </ul>
  )
}

class Child extends Component {
 handleSpanClick=(e)=>{
     console.log("It works!")
 }
 render(){
  return(
   <span onClick={this.handleSpanClick}></span>
  )
}
like image 305
Jalal Avatar asked Jan 08 '17 15:01

Jalal


2 Answers

@bunion's answer is correct!

It doesn't trigger your handleSpanClick() handler, because the <span></span> you are rendering is empty.

Either place some content in it, or either tweak the CSS display property - change it to block or inline-block and add some height and width. While developing, you can also set a background color, so you actually see where your <span></span> is.

You're code is just fine. Here's a prove, run this snippet:

class Menu extends React.Component {
  handleItemClick=(e)=>{ /* whatever .. */ }
  render() {
    return(
      <ul>
        { this.props.items.map((item, i) => (
          <li key={i} id={i}
            onClick={this.handleItemClick}>
            <Child />
          {item}
          </li>
        ))}
      </ul>
    )
  }
}

class Child extends React.Component {
  handleSpanClick=(e)=>{ console.log("It works!"); }
  render(){
    return (
      <span onClick={this.handleSpanClick}>
        CLICK ME (I am span)
      </span>
    );
  }
}

ReactDOM.render(<Menu
  items={[
    '-- I am list item, 1',
    '-- I am list item, 2',
    '-- I am list item, 3'
  ]} />,
  document.getElementById('app')
);
/* So we could see better where it is */
span {
  background-color: lightgreen;
  cursor: pointer;
}
<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="app"></div>
like image 111
Kaloyan Kosev Avatar answered Nov 15 '22 10:11

Kaloyan Kosev


This looks like its probably because the span defaults to an inline element and if you haven't styled it will have 0 width so it wont have a clickable area. Try putting some text in so it actually has a clickable area to test. If this works style it with CSS (display: block, width, height etc).

like image 1
plarner7 Avatar answered Nov 15 '22 10:11

plarner7