Home > Back-end >  passing react hooks into component
passing react hooks into component

Time:09-26

I'm new to React. I'm trying to add additional functionality of deleting the record from the list by setting the value.

here is my App.js

import React, { useState } from "react";
import data from "./data";
import List from "./List";

function App() {
  const [movies, setMovie] = useState(data);

  return (
    <main>
      <section className='container'>
        <h3>{movies.length} Movies to Watch</h3>
        <List movies={movies} setMovie />
        <button onClick={() => setMovie([])}>clear all</button>
      </section>
    </main>
  );
}

export default App;

In List.js, Im trying to delete the record when clicking on Watched button. Can I call setMovie inside the List component? is it a correct way?

List.js

import React from "react";

const List = ({ movies }, setMovie) => {
  return (
    <>
      {movies.map((movie) => {
        const { id, name, year, image } = movie;
        return (
          <article key={id} className='person'>
            <img src={image} alt={name} />
            <div>
              <h4>{name}</h4>
              <button
                className='btn'
                onClick={(id) =>
                  setMovie(movies.filter((movie) => movie.id !== id))
                }
              >
                watched
              </button>
              <p>{year}</p>
            </div>
          </article>
        );
      })}
    </>
  );
};

export default List;

enter image description here

CodePudding user response:

You have two mistakes in your code. First:

<List movies={movies} setMovie />

This shorthand assigns a value of true to setMovie. To assign the setMovie function to it, you must instead do:

<List movies={movies} setMovie={setMovie} />

And secondly this:

const List = ({ movies }, setMovie) => {

Should be this:

const List = ({ movies, setMovie }) => {

CodePudding user response:

try:

<List movies={movies} setMovie={setMovie} />

this way the funcition will appear in the List component as a prop.

The way you were doing, it will just appear as true

  • Related