useMapContext
The useMapContext
hook provides an easy way to access the dimensions of the map as well as some useful helpers for developing custom components.
import { forwardRef } from "react"
import { ComposableMap, useMapContext } from "react-simple-maps"
const CustomLine = forwardRef(
({ coordinates = [[0, 0], [0, 0]] ...restProps }, ref) => {
const { projection } = useMapContext()
const [x1, y1] = projection(coordinates[0])
const [x2, y2] = projection(coordinates[1])
return <line x1={x1} y1={y1} x2={x2} y2={y2} {...restProps} />
}
)
...
<ComposableMap>
<CustomLine
coordinates={[[151.21, -33.87], [-74, 40.71]]}
strokeWidth={3}
stroke="#000000"
/>
</ComposableMap>
jsx
The above CustomLine
would render a straight line across the map from Sydney to New York, instead of trying to find the shortest geographic route as a lineString from Sydney to New York that could be interrupted, depending on the projection used.
Returned values
The following properties are returned by the useMapContext
hook.
projection()
The projection function can be used to project points specified as longitude
and latitude
to x/y coordinates that can be used in SVG.
import { useMapContext } from "react-simple-maps"
const CustomPoint = () => {
const { projection } = useMapContext()
const [x, y] = projection([151.21, -33.87])
return <circle cx={x} cy={y} r={10} fill="#06F" />
}
jsx
path()
The path function can be used to render out custom shapes based on a geojson geometry.
import { useMapContext } from "react-simple-maps"
const CustomLine = () => {
const { path } = useMapContext()
const d = path({
type: "LineString",
coordinates: [
[-80, 0],
[80, 0],
],
})
return <path d={d} stroke="#06F" strokeWidth={3} />
}
jsx
width
The width property returns the width
attribute specified on the ComposableMap
component. This property can be used to render elements in relation to the viewBox
used by the SVG container.
height
The width property returns the height
attribute specified on the ComposableMap
component. This property can be used to render elements in relation to the viewBox
used by the SVG container.