I am trying to use the library react-leaflet and I want to open a modal when we click on a button on the popup but I do not achieve to do that.
Here is my code:
import React from "react";
import { Map, TileLayer, Marker, Popup } from "react-leaflet";
import { defaultMarker } from "./defaultMarker";
import { popupContent, popupHead, popupText, okText } from "./popupStyles";
import "./Map.css";
const center = [51.505, -0.09];
const MapComp = () => {
return (
<Map style={{ width: "100%", height: "100vh" }} center={center} zoom={13}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={center} icon={defaultMarker}>
<Popup className="request-popup">
<button>Open Modal</button>
</Popup>
</Marker>
}
</Map>
);
};
export default MapComp;
You can see the full code there:
https://codesandbox.io/s/how-to-style-the-react-leaflet-popup-forked-7yozy?file=/src/Map.js:0-788
I just open a modal when I click on the popup and I click on the button "Open Modal"
Thank you very much !
You can use react-bootstrap
which includes react components for bootstrap library or reactstrap
. Both makes it easier to play with bootstrap components otherwise you will have to create your own and manipulate the state by yourself.
Here is an example with react-bootstrap
:
Install the library npm i react-bootstrap
Create a Modal component:
function CustomModal({ show, onClose }) {
return (
<Modal show={show} onHide={onClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={onClose}>
Close
</Button>
<Button variant="primary" onClick={onClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
);
}
On your Map import your custom modal and handle its state to be able to show hide it upon button press
const MapComp = () => {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
return (
<>
<Map style={{ width: "100%", height: "100vh" }} center={center} zoom={13}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={center} icon={defaultMarker}>
<Popup className="request-popup">
<button onClick={() => setShow(true)}>Open Modal</button>
</Popup>
</Marker>
</Map>
<Modal show={show} onClose={handleClose} />
</>
);
};
Edit
It seems that there is a bug with react-bootstrap
library. When you open the modal and then you close it, the map freezes unexpectedly and you cannot interact with it.
I installed and reproduced it with reactstrap
and there is no such an issue.
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.