Skip to content
Advertisement

Triggering a function via onClick with a React-Bootstrap ListGroup

Given two components, one just being the render of a react-bootstrap ListGroup, and the other being a function containing a console.log print out, I’m running into trouble seeing that printout when using onClick in the listgroup item. I’m building a music player and the list group contains songs to click on.

When I try to remove <Player Player = /> from the ListGroupItem, it becomes a span element instead of a button. I could print a console.log from within the div but I was going to use the handleClick function to start working on song switching, and as the function is listed as undefined I’m kinda stuck.

In player.js (where the actual music player component is contained)

  handleClick = (e) => {
    e.preventDefault();
    console.log('hello');
  }

In Songlist.js

class Songlist extends Component {
  constructor(props) {
    super(props);
  }
 Songlist = () => {
    return(
       <div className="listgroup">
        <ListGroup>
          <ListGroupItem onClick=<Player Player = {this.handleClick} />>
          button text goes here
          </ListGroupItem >
          //more list group items go here
         </ListGroup>
        </div>
          );
        }


 render() {
    return (
      <div className="Songlist">
      {this.Songlist()}
      </div>
    );
  }
}

export default Songlist;

The actual error message I’m getting is “Error: Expected onClick listener to be a function, instead got a value of object type.” But since I’m using an arrow function nothing needs to be bound, and I’m pretty sure that’s the syntax for passing a function to an onClick listener no?

Advertisement

Answer

You need to do the following because onClick expects a function, instead of the object you are giving it.

 <ListGroupItem onClick=<Player Player = {this.handleClick} />>

should become

 <ListGroupItem onClick={() => <Player Player = {this.handleClick} />}>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement