Home > Blockchain >  Passing function through props in ReactJS
Passing function through props in ReactJS

Time:12-08

Here are two components one is Home.js and other is BlogList.js I am passing handleDelete() as a prop into BlogList and using it as a function in Home.js.

Home.js

import {useState} from 'react';
import BlogList from './Bloglist';

const Home = () => {
    const handleDelete = (id) =>{
        console.log(id);
    }

    const [blogs ,setBlogs] = useState([
    { title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },
    { title: 'Welcome party!', body: 'lorem ipsum...', author: 'Akks', id: 2 },
    { title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }
    ])
    
    return ( 
<div className="home">
<BlogList blogs={blogs} title="All Blogs"/>  
<BlogList blogs={blogs.filter((blog)=>blog.author==="mario")} handleDelete={handleDelete}/>
</div>
     );
}
 
export default Home;

blogList.js

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

But it is showing error that handleDelete is not a function

CodePudding user response:

since your handleDelete is optional prop in BlogList component, you should first check if it's defined when passing it as onClick handler to button:

<button onClick={handleDelete ? () => handleDelete(b.id) : undefined}></button>

Also, you should check prop-types package on NPM or at least basic typescript to avoid similar errors in future.

  • Related