简体   繁体   中英

How to add items to the watchlist in reactJs?

I Am trying to figure out how can I add the items to watchlist,

The steps am trying to carry out here are, when a user clicks on add button, the items should be added to the watchlist page/component which I have created.

Please see the hierarchy of the component. I would like to show added items on the watchlist page.

在此处输入图像描述

Please see the code I tried.

const [watchlist, setWatchlist] = useState ([]);

const handleWatchlist = (movieData) => {
   const newList = [...watchlist, movieData]
   setWatchlist(newList)
   console.log(newList)
}




<Button className = {classes.cardButton}size = "small" onClick = {  ()=> handleWatchlist(movie) }> Add </Button>

When I try to inspect, the result is, it shows the items are added but can not pass on to the watchlist component? How can use a prop to pass this value and show them?

![在此处输入图像描述

Any help is really appreciated.

Thanks a million

The Button doesn't pass any argument in handleWatchlist in your example. I don't know how Button component looks like, but passing the arg could look like the example below:

const Button = ({ onClick }) => {

  const value = "some value";

  return <button onClick={() => onClick(value)}>Button</button>;
};

const WatchList = () => {
...
return <Button onClick={handleWatchlist}>Add</Button>

Thanks for the support, but I figured out the solution by using two approaches and they are

Which is props drilling, ie is to perform the useState action in my App.js which is my main page where I have product and watchlist component.

This is the best way I would suggest other people use as well is by using the contextAPI and useContext hooks . A simple and easy way to pass any data anywhere in the app.

Please see the full code with the working solution below on the codesandbox.

https://codesandbox.io/s/determined-nightingale-m2mtn?file=/src/components/Products

The working app, where I can add the products to the watchlist.

working demo app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM