Home > Enterprise >  TypeError: (X) is not a function
TypeError: (X) is not a function

Time:10-23

I'm working on that simple react project . I am now trying to call onClick function that calls handleDelete function that enables to delete a blog from his 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?

CodePudding user response:

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

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