How to use props or send data from one component to other?

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.

enter image description here

Please see the code I tried.

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

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




<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?

[enter image description here

Any help is really appreciated.

Thanks a million

setWatchlist is a Function. You should not log it to console. Try that line as

   console.log(watchlist)

You can also try this

const handleWatchlist = movieData  => {
   setWatchlist(prevList = > [..prevlist, movieData])
   console.log(Watchlist)
}
1 Like

Hi @ajayraja

Thanks a million sir, it did work I can see that now on console, I just passed newlist as shown below


console.log(newlist)

however just final quest how can I pass this data to another component?
can I do something like as below?

const handleWatchlist = (movieData) => {

        const newList = [...watchlist, movieData]

        setWatchlist(newList);  

        console.log(newList);

        return(

            <Watchlist watchlist = {watchlist}/>

            );

       

    }

This is how my watchlist component looks like. I think I might have to use map method to show added data, but am not sure is it the right way am thinking. Please correct me sir.

import React from 'react';

import {Card, CardActionArea, CardContent, CardMedia, Typography } from '@material-ui/core';

import Rating from '@material-ui/lab/Rating';

const Watchlist = (newList) => {

   

    return (

        <>

          <Card className={'classes.cardMain'}  key={newList.id}>

                    <CardActionArea>

                        <CardMedia className = {'classes.cardImage'}>

                            <img style = {{width: '100%', height: '100%', objectFit: 'cover'}}

                                src ={`https://image.tmdb.org/t/p/original${'movie.poster_path'}`}

                                alt = "movie poster"/>

                        </CardMedia>

                        <CardContent className = {'classes.cardContent'}>

                            <Typography>  {newList.original_title} </Typography>

                            <Typography

                                        className = {'classes.typography1'}

                                        variant="body2"

                                        component = "p"

                                > {'movie.release_date'}

                                </Typography>

                            <Rating

                                    className = {'classes.typography2'}

                                    name = "ratings"

                                    value =  {'movie.vote_average/2'}

                                    precision={0.5}

                                    readOnly                                

                            />  

                           

                        </CardContent>

                    </CardActionArea>

                    </Card>

   

    </>

    )

}

export default Watchlist;

The result on my watchlist page

Thanks again for your help Ajay sir

Kind Request

Don’t call me sir, I’m just 16. Use Ajay instead.

Link to learn for you

About props

Javacsript Map

Javascript Map with React

const handleWatchlist = (props) => {
    const newList = [...props.watchlist, movieData]
    setWatchlist(newList);  
    console.log(newList);
    return(
        <Watchlist watchlist = {watchlist}/>
        );
}

If watchlist array was like

[
  {
  original_title: "Any Movie", 
  poster_path: "url",
  release_date: "Any Data",
  vote_average: 5
  },
  {
  original_title: "Any Movie", 
  poster_path: "url",
  release_date: "Any Data",
  vote_average: 5
  },
  // Any data like above
]
import React from "react"; 
import {Card, CardActionArea, CardContent, CardMedia, Typography } from '@material-ui/core';
import Rating from '@material-ui/lab/Rating';

const WathList = (props)=>{
  return (
    {
  props.newList.map(movie=>
  <Card className={'classes.cardMain'}  key={newList.id}>
    <CardActionArea>
        <CardMedia className = {'classes.cardImage'}>
            <img style = {{width: '100%', height: '100%', objectFit: 'cover'}}
                src ={`https://image.tmdb.org/t/p/original${'movie.poster_path'}`}
                alt = "movie poster"/>
        </CardMedia>
        <CardContent className = {'classes.cardContent'}>
            <Typography>  {movie.original_title} </Typography>
            <Typography
                className = {'classes.typography1'}
                variant="body2"
                component = "p"
            > {'movie.release_date'}
                </Typography>
            <Rating className = {'classes.typography2'}
                name = "ratings"
                value =  {'movie.vote_average/2'}
                precision={0.5}
                readOnly                                
            />
        </CardContent>
    </CardActionArea>
  </Card>
      )
    }
  )
}

I hope It would help you and Sorry for delay to answer.

Thats all okay Ajay no worries. and good to see your passion for coding at the age of 16, just amazing.

However the code you provided does not work fine for me, shows that props.newlist.map is invalid argument…

Is there any thing missing from my side?

Thanks

Its hard for me to figure out where is the button which modify the watchlist state and where is the watchlist component? Are they parent and child elements, or do they share the same parent?

Sorry mistake is on me. Typo in my code change props.newList.map as watchlist.

Is it works ? Reply whether It works or not.

Hi @ajayraja
Thanks a million for the help but I have figured about the solution to this,
@Sylvant thanks for the support yeah they share the same parent, as the are inside the app.js which is main component.

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

  1. Which is props drilling, i.e. is to perform the useState action in my App.js which is my main page where I have product and watchlist component.
  2. 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.

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

working demo app

1 Like

this is what i was about to suggest(once i knew in what sense the two elements are connected). You can either store the state in the parent component and pass to the button the function to modify the state, while pass to the watchlist the state value. Or the other solution to use context to store the app state and give access to components which use it. Ofc both solutions would make components involved in the state change to be rerendered, but this is something you shouldnt worry for smaller apps

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.