Trying to use a Button component, but the onClick doesn't seem to work with it. How do I pass method to the Button component?
If I use a standard the onClick works.
onClick does nothing here.
child Component
const buttonStyleDelete = {
backgroundColor:'red'
}
const handleClick = (e) => {
e.preventDefault()
axios.delete("/api/emails/delete/", {
data: {email: email}
}).then(() => onDelete())
}
const EmailItem = ({email, onDelete}) => (
<div>
<h3>{email}</h3>
<Button
onClick={(e) => handleClick(e)}
buttonStyle={buttonStyleDelete}
buttonLabel={'Delete'}
>
Remove
</Button>
</div>
)
Parent Component
hideEmail = () => this.fetchEmails()
fetchEmails = () => {
fetch("/api/emails/")
.then(res => res.json())
.then(parsedJSON => parsedJSON.map(emails => ({
email: `${emails.email}`,
id: `${emails.id}`
}))).then(emails => this.setState({allEmails: emails}))
}
render() {
return (
<div>
<h2>Admin Page</h2>
<div>
{this.state.allEmails.map((email) => {
return <EmailItem
key={email.id}
email={email.email}
onDelete = {() => this.hideEmail()}/>
})}
</div>
</div>
);
}
}
email
and onDelete
are not in scope in the handleClick
function. You could pass them in as arguments instead.
const buttonStyleDelete = {
backgroundColor: "red"
};
const handleClick = (e, email, callback) => {
e.preventDefault();
axios
.delete("/api/emails/delete/", {
data: { email: email }
})
.then(() => callback());
};
const EmailItem = ({ email, onDelete }) => (
<div>
<h3>{email}</h3>
<Button
onClick={e => handleClick(e, email, onDelete)}
buttonStyle={buttonStyleDelete}
buttonLabel={"Delete"}
>
Remove
</Button>
</div>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With