Reputation: 109
I want to pass a function from parent (PendingRides) to child( ThirdSidebar)
But getting error _this.props.onclk is not a function.I have bind the function with this but still getting error.
class PendingRides extends React.Component {
//Parent Class
constructor(props) {
super(props);
this.switchclk=this.switchclk.bind(this);
this.state={
clk:false
}
}
switchclk = (status)=>{
console.log("Here2");
this.setState({clk:status})
};
render(){
return(
<div>
<ThirdSidebar onclk={this.switchclk}/> // passing function to child
{this.state.clk ?
<div>
<div className="layout-content">
<div className="layout-content-body">
</div>
</div>
</div>
:null}
</div>
)
}
}
class ThirdSidebar extends React.Component{
constructor(props){
super(props);
this.showRides=this.showRides.bind(this);
this.state={
}
}
showRides = (e)=>{
e.preventDefault();
console.log("Here1");
this.props.onclk(true)
};
render(){
let hreflink=null;
return(
<div>
<div className="layout-main"> {/*---------------------- sidebar ----------------------- */}
<div className="layout-sidebar">
<div className="layout-sidebar-backdrop">
</div>
<div className="layout-sidebar-body">
<div className="custom-scrollbar">
<nav id="sidenav" className="sidenav-collapse collapse">
<ul className="sidenav-subnav">
<li className="sidenav-subheading">Dashboards</li>
<li onClick={(e)=>this.showRides(e)} className="active"><a href={hreflink}>Pending Rides</a></li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div> {/* sidebar ends */}
</div>
</div>
)
}
}
export default ThirdSidebar
When the user clicks on pending rides it calls the function of showRides,where I am receiving props and getting error in child component
Upvotes: 0
Views: 671
Reputation: 20755
In your PendingRides
component your switchclk
function should be this,
switchclk(status){ //Remove arrow function
console.log("Here2");
this.setState({clk:status})
};
In your ThirdSidebar
component your showRides
function should be this,
showRides(e){ //Remove arrow function
e.preventDefault();
console.log("Here1");
this.props.onclk(true)
};
Call above function like this,
<li onClick={this.showRides} className="active"><a href={hreflink}>Pending Rides</a></li>
Note: How to use arrow functions
Upvotes: 1
Reputation: 7004
If you use arrow function you don't need to bind your function anymore.
Actually, arrow function is an equivalent of bind()
.
Remove your bind line:
this.showRides = this.showRides.bind(this); // to remove
Or change arrow function with:
showRides (e) {
e.preventDefault();
console.log("Here1");
this.props.onclk(true)
};
Upvotes: 0