Reputation: 23
I've been looking through related posts and tried a few solutions but I wasn't able to adapt any of them to my situation.
I am trying to change the state of selectedPin
by sending the function and calling it from the child component.
See below my code
Parent component :
export default function Pins(data) {
const chargers = data.data;
const [selectedPin, setSelectedPin] = useState(null);
const handleClose = () => {
setSelectedPin(null);
};
return (
<>
{chargers.map((charger, index) => (
<Marker
key={index}
longitude={charger.AddressInfo.Longitude}
latitude={charger.AddressInfo.Latitude}
>
<Button
onClick={(e) => {
e.preventDefault();
setSelectedPin(charger);
}}
>
<img src="./assets/pin.svg" alt="marker pin" />
</Button>
</Marker>
))}
{selectedPin ? (
<PopupInfo selectedPin={selectedPin} handleClose={handleClose} />
) : null}
</>
);
}
Child component :
export default function PopupInfo(selectedPin, { handleClose }) {
const pin = selectedPin.selectedPin;
console.log(pin);
console.log(handleClose);
return (
<Popup
latitude={pin.AddressInfo.Latitude}
longitude={pin.AddressInfo.Longitude}
onClose={handleClose}
>
<div>Popup Info</div>
</Popup>
);
}
When console logging handleClose
in child component I am getting undefined
.
Upvotes: 1
Views: 377
Reputation: 122
It won't work as React is Uni-directional data flow model - it'a core feature of React.
State of Parent can't be modified by Child. You have to come-up with an idea to handle the data in Parent itself or pass that as prop to bypass(not recommended)
If you are interested to know more : https://www.youtube.com/watch?v=hO8u07-WTOk
Upvotes: 0
Reputation: 7652
I think you should pass them both down as named props:
export default function PopupInfo({ selectedPin, handleClose })
or do this:
export default function PopupInfo(props)
and then use props.selectedPin
and props.handleClose
.
Upvotes: 1