Home > OS >  Calling useNavigate('url') inside layer.click() is not working
Calling useNavigate('url') inside layer.click() is not working

Time:12-11

In this project, I'm using react leaflet to show a map which generated by GEOJSON features object. I just to go to a dynamic country route when clicking on each of the country layer.

const geoJsonRef = useRef();
useEffect(()=>{
    geoJsonRef.current.getLayers().map((layer)=>{
        layer.on({
            click : ()=>{
                useNavigate( 'go/to/country' ); // here is the error occurs
            }
        });
    });
}, [state]);
return(
    <MapContainer style={containerStyle} center={[10, 0]} zoom={2} minZoom={2.4} maxZoom={10}>
        <GeoJSON style={contryStyle} data={features} onEachFeature={onEachCountry} ref={geoJsonRef} />
    </MapContainer>
);

Error:

React Hook "useNavigate" is called in function "click" that is neither a React
function component nor a custom React Hook function. React component names
must start with an uppercase letter. React Hook names must start with the word "use" 
react-hooks/rules-of-hooks

From this error I can understand that, it is incorrect way of using useNavigate(). The same I got when attaching the click handler in the onEachCountry function. I just need to know the correct way click handler to give the route.

Thank you!

CodePudding user response:

React hooks can only be called from React function components or custom hooks, they cannot be called in callbacks, conditions, and loops as this breaks the Rules of Hooks.

Call the useNavigate hook first in the component body to return the navigate function, then call navigate in any callback/hook/etc...

const navigate = useNavigate();

useEffect(() => {
  geoJsonRef
    .current
    .getLayers()
    .map((layer) => {
      layer.on({
        click: () => {
          navigate('go/to/country');
        }
      });
  });
}, [state]);
  • Related