React prop function undefined [duplicate]
I have an element that has an onClick prop, and then another element which calls this prop, and does some other operations.
Here is the code:
DashboardSidebar:
class DashboardSidebar extends Component{
constructor(props){
super(props);
this.expandOption = this.expandOption.bind(this);
}
expandOption(id){
...
}
render(){
return(
<div className="DashboardSidebar">
...
<DSidebarOption onClick={this.expandOption("dashboard")} id="dashboard" text="Dashboard" />
...
</div>
);
}
}
DSidebarOption:
class DSidebarOption extends Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
...
this.props.onClick();
...
}
render(){
return(
<div className="DSidebarOptionContainer">
...
<div onClick={this.handleClick} className="DSidebarOption">
{this.props.text}
</div>
...
</div>
)
}
}
I am getting the following error:
Uncaught TypeError: this.props.onClick is not a function
Any ideas why this might be happening?
You should pass ur onclick like this
onClick={() => {this.expandOption("dashboard")}}
otherwise it gets called when the page mounts