Yassel
Yassel

Reputation: 87

TypeError: (X) is not a function

I'm working on a simple React project. I am now trying to call the onClick function that calls the handleDelete function that enables to delete a blog item from its id.

Here is the BlogList component:

const BlogList = ({blogs,title,handleDelete}) => {
    return (
        <div className="blog-list">
            <h2>{ title }</h2>
                {blogs.map((blog) => (
                    <div className="blog-preview" key={blog.id}>
                        <h2>{ blog.title }</h2>
                        <p>written by { blog.author}</p>
                        <button onClick={() => handleDelete(blog.id)}>delete blog</button>
                    </div>
                ))}
        </div>
    );
}

export default BlogList;

Here is the Home component:

import { useState } from "react";
import BlogList from "./blogList";

const Home = () => {
    const [blogs, setBlogs] = useState([
        { title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },
        { title: 'Welcome party!', body: 'lorem ipsum...', author: 'yoshi', id: 2 },
        { title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }
    ])

    const handleDelete = (id) => {
        const newBlogs = blogs.filter(blog => blog.id !== id);
        setBlogs(newBlogs);
    }

    return (
        <div className="home">
            <BlogList blogs={blogs} title='All blogs'/>
        </div>
    );
}

export default Home;

When I click on the delete blog button in the browser, I receive this:

messageTypeError: handleDelete is not a function

What am I missing here?

Upvotes: 0

Views: 871

Answers (1)

Jirka Svoboda
Jirka Svoboda

Reputation: 418

You have to pass your handler as a prop to BlogList component. Like this:

<BlogList blogs={blogs} title='All blogs' handleDelete={handleDelete} />

Upvotes: 1

Related Questions