Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

reactjs - Render Map child from outside MapContainer

I would like to render a child inside <MapContainer> from outside the initial MapContainer. Is this possible somehow?

In react-leaflet-v3 I render a lot of items on the map by passing the map object via a reference. But for my current situation I wold like to render a react button on top of the map based on routing.

One way of doing this is to add nest <Route />. inside the MapContainer. This however is not ideal because of the scattered route behaviour...

Is it possible in another way?

question from:https://stackoverflow.com/questions/65921661/render-map-child-from-outside-mapcontainer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I used the portal way to solve my problem:

In my map-container, this is happens:

const [control, setControl] = useState(null);
const handleRef = useCallback((instance) => setControl(instance), [
  setControl,
]);
...


<MapContainer ...>
   ...
   <div className="mapcontrol-top-left" ref={handleRef}></div>
</MapContainer>

In a totally different component, where conditionally I want to show something on the Map, I do this (using Material-UI Portal & Fab component):

<Portal container={props.control}>
  <Fab size="medium">
    <EditIcon />
  </Fab>
</Portal>

The material-ui Portal component is easy to use and add convenience, but a native React Portal will also dot he trick...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...