I'm struggling to make a React/JS map I have more efficient. Essentially, I have a list of cards, and then a map of markers. When I hover on one of the cards, it changes the styling of the marker.
Here’s what it looks like:
But the way I'm doing this...I'm pretty sure is really inefficient, so here's how I have it setup in a couple of components:
//LocationsGrid.js
class LocationsGrid extends React.Component {
state = {
hoveredCardId: ""
};
setCardMarkerHover = location => {
this.setState({
hoveredCardId: location.pageid
});
};
resetCardMarkerHover = () => {
this.setState({
hoveredCardId: ""
});
};
render() {
const { locations } = this.props;
{locations.map((location, index) => (
<LocationCard
setCardMarkerHover={this.setCardMarkerHover}
resetCardMarkerHover={this.resetCardMarkerHover}
location={location}
/>
))}
// map stuff
<div className={classes.mapDiv}>
<MapAndMarkers
locations={locations}
hoveredCardId={this.state.hoveredCardId}
/>
</div>
//LocationCard.js
class LocationCard extends React.Component {
render() {
const { classes, location } = this.props;
return (
<Card
className={classes.card}
onMouseEnter={e => this.props.setCardMarkerHover(location)}
onMouseLeave={e => this.props.resetCardMarkerHover()}
>
<CardContent className={classes.cardContentArea}>
</CardContent>
</Card>
);
}
}
// MapAndMarkers.js
class MapAndMarkers extends React.Component {
render() {
const { locations, hoveredCardId, pageid } = this.props;
let MapMarkers = locations.map((location, index) => {
return (
<MapMarker
key={location.id}
lat={location.lat}
lng={location.lng}
pageid={location.pageid}
hoveredCardId={hoveredCardId}
/>
);
});
return (
<div>
<GoogleMapReact>
{MapMarkers}
</GoogleMapReact>
</div>
);
}
}
// MapMarker.js
import classNames from 'classnames';
class MapMarker extends React.Component {
render() {
const { classes, pageid, hoveredCardId } = this.props;
return (
<div className={classes.markerParent}>
<span className={classNames(classes.tooltips_span, pageid == hoveredCardId && classes.niftyHoverBackground)}>{this.props.name}</span>
</div>
);
}
}
The problem with doing it this way is I'm pretty sure there's a whole bunch of wasted rendering. When I pulled out the mouse events from my LocationCard
, everything else runs faster.
What would be a more efficient way of tracking hovered list items so that I can change the map marker style?