简体   繁体   中英

React-Leaflet - Custom Pin, OnClick Link to another page

I have a react-leaflet integration with custom pins (Via divIcon)

const divIcon = L.divIcon({
      className: '',
      html: ReactDOMServer.renderToString(
          <CustomPin pinColour={pinColour} pinCode={pinCode} pinID={id} history={history} />
      ),
      iconSize: [24, 40],
      iconAnchor: [12, 40],
      popupAnchor: [0, -40]
});

If I want to do a redirect when the user clicks the custom icon, how can I do this?

Including a tag in the ReactDOMServer.renderToString is obviously not possible.

Is there a work around for this?

Define two routes on index.js:

const App = () => {
  return (
    <Router>
      <Route exact path="/" component={MapLeaflet} />
      <Route path="/another-page" component={AnotherPage} />
    </Router>
  );
};

MapLeaflet will be the component which will contain your map and AnotherPage for instance another component that you will be redirected to after clicking the marker.

Then in your MapLeaflet comp

<Marker
    position={position}
    icon={customMarker}
    onClick={() => this.props.history.push("/another-page")}>

use onClick event to navigate to another-page route from the Marker

I have included optionally the possibility to navigate back to '/' route from AnotherPage comp.

Also I used L.icon instead of L.divIcon . Hopefully it is ok for you.

Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM