How to pass function as props from one functional component to another?

Viewed 7088

I'm passing a function as prop from one functional component(Dashboard) to another (Event).However, When I'm clicking the button on the child component which holds the passed function prop on the onClick value , it throws an error.

Uncaught TypeError: deleteEvent is not a function

This my deleteEvent fucntion in Dashboard

  const deleteEvent = async (id) => {
    try {
      await Axios.delete(`/event/${id}`);
      const events = data.events.filter((event) => event.id !== id);
      setData({ ...data, events: events });
    } catch (err) {
      console.log(err);
    }
  };

This is how I'm rendring events in Dashboard.

{data.events.map((event, idx) => (
        <Event key={`event${idx}`} event={event} delete={() => deleteEvent} />
      ))}

Here's my Event.jsx

const Event = ({
  event: { id, name, price, duration, schedule },
  delete: { deleteEvent },
}) => {
  console.log(deleteEvent);
  return (
    <div className="event" key={id}>
      <p>Name: {name}</p>
      <p>Price: {price}</p>
      <p>Duration - {duration}</p>
      <p>Schedule</p>
      {Object.keys(schedule).map((day) => (
        <p key={day}>
          {day} -{' '}
          {schedule[day].map((slot, idx) => (
            <span key={idx}>
              {slot.start} - {slot.start}
            </span>
          ))}
        </p>
      ))}
      <button type="button" onClick={() => deleteEvent(id)}>
        Delete Event{' '}
      </button>
    </div>
  );
};

When I click the button , it thorws Uncaught TypeError: deleteEvent is not a function error.

What am I doing wrong ? I've done this using class based components before.

1 Answers

When you're passing in the delete() function you are creating an anonymous function that returns the delete() function handle, instead of passing the function itself in.

Where you have

delete={() => deleteEvent} />

you could just pass the function itself as a prop

delete={deleteEvent} />

In the destructuring inside the Event code you would just need to access the function back out under the delete key instead of wrapping it in a second set of curleys to pull an object

delete: deleteEvent

Related