Styling
There are a number of ways in which you can style your maps in react-simple-maps. Depending on the app you are building and the way in which you handle interactivity, you may choose to either style your map via svg attributes, the style property, or to wrap the react-simple-maps components using styled-components
, emotion
or a similar library.
SVG attributes
One of the easiest ways in which to add basic styles to your shapes is to use svg attributes like fill
and stroke
.
Using the following code would render geographies in a bright orange with a black border:
<Geographies geography="/topojson-file.json">
{({ geographies }) =>
geographies.map((geo) => {
return (
<Geography
key={geo.rsmKey}
geography={geo}
fill="#FF5533"
stroke="#000000"
/>
)
})
}
</Geographies>
jsx
Svg attributes are an ideal candidate if you are using generated colors (based on a scale), like you would when you are making a choropleth map:
import { scaleLinear } from "d3-scale"
const colorScale = scaleLinear().domain([0, 100]).range(['#FFF', "#06F"])
...
<Geographies geography="/topojson-file.json">
{({ geographies }) =>
geographies.map((geo) => {
return (
<Geography
key={geo.rsmKey}
geography={geo}
fill={colorScale(geo.properties.exampleValuePerCapita)}
/>
)
})
}
</Geographies>
jsx
Style prop
If you want to use dynamic styles that change when the user interacts with the map, you may want to use the style prop in react-simple-maps. This prop does not behave exactly like the style
prop of any regular html element.
The style
property can be used to define the default
, hover
, and pressed
state of a geography. React-simple-maps will then dynamically replace the inline styles with the styles specified here.
<Geographies geography="/topojson-file.json">
{({ geographies }) =>
geographies.map((geo) => {
return (
<Geography
key={geo.rsmKey}
geography={geo}
style={{
default: {
fill: "#EEE",
},
hover: {
fill: "#F53",
},
pressed: {
fill: "#E42",
},
}}
/>
)
})
}
</Geographies>
jsx
This method offers the maximum flexibility in styling a map and keeps all of your styles directly in the map. In the case that your visualisation relies heavily on generated colors based on scales, this method provides the best option for flexible styling.
Wrapping
You can wrap react-simple-maps components using a library like styled-components, emotion, or other similar styling libraries.
import { styled } from "@emotion/styled"
import { Geography } from "react-simple-maps"
const StyledGeography = styled(Geography)`
fill: #06f;
`
jsx
If you are using a component library like chakra-ui, you can also wrap react-simple-maps components with chakra
.
import { chakra } from "@chakra-ui/system"
const ChakraGeography = chakra(Geography)
...
<Geography _hover={{ fill: "#F53" }} />
jsx