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> ) } 

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=""></script> <script src=""></script> <div></div>
4

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).

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like