'I am trying to pass a function as a prop to my component
I have an Activity.js Component that I am bringing in to my App.js component that renders activities. I would like add an onlick event to a button in this component by passing a function as a prop to that button, for some reason the button isnt working, right now its a simple console.log for the logic.
The activities do display when I map through the array of objects but it seems the button isn't taking the props. Can somebody help me understand my why deleteActivity function doesn't run when I click the button?
Acitivity.js component
import React, {Component} from 'react'
export default function Activity(props) {
return (
<div>
<h1>Things I like to do </h1>
{props.activities.map((activity) => (
<div key={activity.activity} style={{ display: "flex", justifyContent: "space-between" }}>
<li >{activity.activity}</li>
<button onClick={() => props.deleteActivity}>X</button>
</div>
))}
</div>
);
}
App.js Component
import React, { Component } from 'react';
import ListContacts from './ListContacts';
import Activity from './Activity'
class App extends Component {
state = {
activities : [
{
id: 1,
activity: "pool"
},
{
id: 2,
activity: "games"
},
{
id: 3,
activity: "sports"
}
]
}
deleteActivity = ()=>{
console.log("hello")
}
render() {
return (
<div>
<Activity activities={this.state.activities} deleteActivity={this.deleteActivity} />
</div>
)
}}
export default App;
Solution 1:[1]
Youre passing the prop correctly, but you arent actually running the function you passsed. instead of () => { props.deleteActivity }, try adding () to the end of your function. example: () => { props.deleteActivity() }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KyleRifqi |
