Search code examples
javascriptreactjsgoogle-maps-api-3react-hooks

Clicking on an element on google map doesnt scroll to the relevant item on list in react


When I am printing the childElement on the console when clicking on the cards it gets displayed correctly

But when I am trying to use CreateRef to scroll to the card on list when the user clicks on that specific card on Google Maps

Yt Tutorial that I am following skipped to the revelant timestamp : https://www.youtube.com/watch?v=UKdQjQX1Pko&t=5274s

Github Link of the code: https://github.com/adrianhajdin/project_travel_advisor

I am using useEffect like this

(in List.jsx)

const [elRefs, setElRefs] = useState([]);
useEffect(()=> {
    const refs = Array(places?.length).fill().map((_,i)=> elRefs[i] || createRef());
    setElRefs(refs);
},[places]);

Grid Element

<Grid  item key={i} xs={12}>
                    <PlaceDetails 
                    place={place}
                    selected={Number(childClicked) === i} 
                    refProp={elRefs[i]}
                    />

                </Grid>

in (PlaceDetails.jsx)

if(selected) refProp?.current?.scrollIntoView({behavior:"smooth", block:"start"})

App.js Code

 const [isLoading, setIsLoading] =useState(false);
 useEffect(()=>{
    setIsLoading(true);
    getPlacesData(bounds.sw,bounds.ne)
        .then((data)=>{
            
            console.log(data);
            setPlaces(data);
            setIsLoading(false);
        })
},[coordinates,bounds]);
<Grid item xs ={12} md={4}>
            <List places ={places}
            childClicked={childClicked}
            isLoading={isLoading}

            />

Now adding a logical block in List.jsx

{isLoading ? (
            <div className={classes.loading}>
                <CircularProgress size ="5rem" />
            </div>
        ) :(FormControl Code)}

Here are two warnings i am getting

  1. React Hook useEffect has a missing dependency: 'elRefs'. Either include it or remove the dependency array

  2. Received false for a non-boolean attribute `$hover


Solution

  • I solved the error by setting

    const [childClicked ,setChildClicked] =useState();
    

    instead of

    const [childClicked ,setChildClicked] =useState(null)
    

    and enclosing the App.js code like

    {isLoading ? (
            <div className={classes.loading}>
                <CircularProgress size ="5rem" />
            </div>
        ) :(<Fragment>FormControl Code</Fragment>)}
    

    instead of

    {isLoading ? (
            <div className={classes.loading}>
                <CircularProgress size ="5rem" />
            </div>
        ) :(FormControl Code)}