4

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>
    );
  }
}

1 Answer 1

3

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>
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.