Home > Blockchain >  React send function as props
React send function as props

Time:12-21

I'm trying to follow a video tutorial, but one part doesn't work for me.

Home.js

import { useState, useEffect } from 'react';
import Bloglist from './components/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);
  };
  
  useEffect(() => {
    console.log('use effect ran');
  });
  
  return (
    <div className="home">
      <Bloglist blogs={blogs} title="All blogs" handleDelete="{handleDelete}" />
    </div>
  );
};

export default Home;

Bloglist.js

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>Scritto da { blog.author }</p>
          <button onClick={() => handleDelete(blog.id)}>Delete blog</button>
        </div>
      ))}
    </div>
  );
};

export default Bloglist;

When I click on "Delete blog" the console says: Uncaught TypeError: handleDelete is not a function, why?

If necessary and if possible I can post the link to the video tutorial

CodePudding user response:

Your prop is being passed in as a string (handleDelete="{handleDelete}".

Functions passed as props need to references to the function definitions themselves or arrow functions.

For it to work, remove the " so that it's:

<Bloglist blogs={blogs} title="All blogs" handleDelete={handleDelete} />

CodePudding user response:

You're passing a string of {handleDelete} into your Bloglist component instead of the reference to the handleDelete function.

You should replace the following line:

<Bloglist blogs={blogs} title="All blogs" handleDelete="{handleDelete}" />

with

<Bloglist blogs={blogs} title="All blogs" handleDelete={handleDelete} />

CodePudding user response:

In your Home.js file, you have passed the handleDelete function to BlogList in quotations. Try doing it like this:

 <Bloglist blogs={blogs} title="All blogs" handleDelete={handleDelete} />
  • Related