Style and Animate a React Leaflet Shape with Custom CSS

Colby Fayock
InstructorColby Fayock

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 10 months ago

In this lesson, you'll learn how to use CSS to style and animate shapes on your React Leaflet map. We'll use the className prop to add a custom class and add CSS to customize our shapes.

Colby Fayock: [0:00] We're going to start off with a map of Bay Lake, Florida. Here we have a couple shapes on the map, to designate the different Disney parks.

[0:05] Inside the code, we're importing { Map, TileLayer, Polygon, Circle } from 'react-leaflet'. You can also see some of the data we're importing to use on our map. We also have set up our TileLayer and a few shapes to get started. To style our shapes, we are already using props like color, weight and opacity.

[0:21] While the props that React Leaflet provide are great, what if we could use CSS? I like to think as Magic Kingdom is special, so we're going to give it a className of circle-magic-kingdom.

[0:32] Now that we have the CSS class, we can go ahead and open up our CSS file where we're going to add some styles. Because we can add a className to it, we can do whatever we want as long as CSS allows it. Let's try giving it the fill of none, a stroke of red and a stroke-width of 5px.

[0:48] If we look in our browser, we can now see the changes. With CSS, we automatically get access to the hover effect. [inaudible] on hover, we make our stroke-width 15px. To make things a little smoother, we can give it a transition for the stroke-width and let's just say .5 seconds. Again, we can see our changes in the browser.

[1:05] Finally, for the full demonstration of CSS, I created a set of keyframes called MagicKingdom. What it does is loop through different strokes so we can change the color. Let's go ahead and define this animation, add a name, tell it to loop forever, and have each loop last 5 seconds. When we look back in our browser, we can see our looping animation.

[1:22] In review, in order to take advantage of CSS, we added a className to our shape, which allowed us to define our custom styles, even animate it, which gave us a more dynamic look for our shape.