How to Code Images in React with SVG

This ad is not shown to multipass and full ticket holders
React Summit US
React Summit US 2025
November 18 - 21, 2025
New York, US & Online
The biggest React conference in the US
Learn More
In partnership with Focus Reactive
Upcoming event
React Summit US 2025
React Summit US 2025
November 18 - 21, 2025. New York, US & Online
Learn more
Bookmark
Rate this content

Did you ever need a hamburger menu icon and you you looked out for one in an icon library? Actually, it's only a few lines of code with SVG. And SVGs combined with React open up a whole new world. You can generate diagram, graphics or animation, make an interactive game or app. Let's walk through the basics of the syntax.

This talk has been presented at React Day Berlin 2024, check out the latest edition of this React Conference.

FAQ

SVGs become powerful when combined with JavaScript, allowing for animations, data visualizations, and interactive elements within React components.

SVGs can be made interactive by assigning event handlers to SVG elements, similar to HTML elements, allowing for dynamic interactions like color pickers or simulators.

Yes, since HTML5, SVGs can be inlined within HTML documents, allowing the use of SVG-specific elements like circle and text within the SVG tag.

The viewBox defines the coordinate system of the SVG, specifying the canvas dimensions and starting point, which helps position elements consistently regardless of the SVG's actual size.

Shapes in SVGs can be styled using fill, stroke, and stroke-width properties, similar to CSS properties for HTML, but specifically for SVG elements.

Path elements in SVGs are freeform shapes built from multiple segments like lines, curves, and arcs, allowing for complex shapes creation.

Transformations in SVGs allow you to modify elements' positions or orientations, like rotating elements around a center point, without recalculating their coordinates.

Bezier curves are used in SVGs for creating smooth curves by defining start, end, and control points that dictate the curve's direction and bend.

In React, complex SVG visuals can be broken down into smaller components, which are assembled together, allowing for interactive and dynamic visualizations.

You can explore more about SVGs and their applications at svgtutorial.com, which provides detailed presentations and examples.

Hunor Márton Borbély
Hunor Márton Borbély
22 min
16 Dec, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Today's Talk is about coding images in React with SVGs. SVGs are powerful when combined with JavaScript and can be used to create interactive elements. Understanding SVG syntax and positioning is important, as SVG elements are limited to SVG-specific elements. The circle element in SVG can be styled and used to create shapes. The rectangle element is commonly used for charting and can be customized. The path element offers flexibility and can be built from multiple segments. Transformations and curves can be used to create complex shapes and animations. Bezier curves, both quadratic and cubic, are useful for bending lines and creating smooth transitions. Advanced features like drawing arcs are available in SVG. For more examples and use cases, visit svgtutorial.com.

1. Introduction to SVG in React

Short description:

Today I'm going to talk about how to code images in React with SVGs. SVGs become very powerful once you start combining them with JavaScript. You can also make things interactive, like in the case of this color picker. And you can take this to the next level and create an editor, like this logic gate simulator. The last example is the Gorillaz game, which uses HTML canvas. HTML canvas and SVG have quite similar concepts.

Hello everyone! My name is Hunor and today I'm going to talk about how to code images in React with SVGs. And if you're wondering why we decode an image, then here's a couple examples.

SVGs become very powerful once you start combining them with JavaScript. In this example, we are joining this watch face with SVG elements and then we are turning the hands of the watch into position with JavaScript. You can also create animations or generate an infographic or a chart. In this case, we are joining this animation with a React component. In case you need to visualize some data, then you can achieve that by combining JavaScript and SVGs. You can also make things interactive, like in the case of this color picker, if I'm dragging these handlers, then the colors are changing, the values are changing. And what's interesting here is that these handlers that I'm dragging are not an overlay on top of an image. These are part of the SVG image itself. So you can assign an event handler to part of an SVG the same way you would assign an event handler to any other HTML element. And you can take this to the next level and create an editor, like this logic gate simulator. This one is fully interactive. So if I'm clicking the inputs, the output will change. I can drag things around, I can add new elements, I can break connections and make new connections. And this whole thing is one big React, is one big SVG that is built up from multiple components. We have a component for this gate, for this gate, for the connections that are connecting the different gates, for the inputs, for the outputs. And then from these small little components that are all built with React, we can just assemble this big SVG.

Now the last example I want to show to you today is this Gorillaz game. And this one is a bit of an Easter egg, because it's not actually using SVG, apart from this windmill that we are going to cover. But this one is using HTML canvas. The reason I still wanted to show to you today is that HTML canvas and SVG have quite similar concepts. They also have basic shapes, like for the buildings in this case. And we can also build up more complex shapes from different path segments, like straight lines and curves and arcs. So in this case, the body of the gorilla is built up from a path that is using straight lines. Then the arm of the gorilla is one big curve that is defined as a quadratic Bezier curve from different properties. And you can define a quadratic Bezier curve the same way basically in HTML canvas and in SVG, even though one is in JavaScript and one is in HTML, but they have the same parameters. So we are going to get back to this once we are talking about curves. And now let's see if I can hit the enemy. And yes! Okay, so after this introduction, let's see the source code of a basic SVG and let's walk through some basic shapes, styling, and some more advanced shapes.

2. Understanding SVG Syntax and Positioning

Short description:

SVG syntax is XML-based and can be inline in HTML. SVG elements are limited to SVG-specific elements and cannot use regular HTML elements. The SVG element has a width, height, and view box property. The view box defines the coordinate system for positioning elements. Images within the view box are positioned using coordinates.

So this one is showing a circle, a red circle, and that's pretty much it. As you see, the syntax is XML-based. And the cool thing about it is that since HTML5, you can just inline this whole thing inside HTML.

Now of course, there are some hard boundaries here. So within the SVG element, we can only have SVG-specific elements, like the circle. We cannot have a header or a paragraph or a div. If you want to have a text, then we can use the text element. If you want to group things together, then we can use the group element. So there are similar elements, but we cannot use the regular HTML elements that we're used to. And this goes the other way as well. So we cannot use the circle element outside of the SVG element because in order to position this circle, we need to have a coordinate system and that is defined by the SVG element.

Of course, we can just generate this whole thing with a React component. And not just like this, but we can also break down a more complex SVG into multiple components and then assemble them together. Now let's take a closer look into the SVG element. As we see, it has a width and a height, and it also has a view box property, which also defines width and a height. So let's look into this. Here we have two images, and they have the same content. Both of these images have a circle with a center position at 100, 100, and the radius of 50. This one is the same exact circle definition.

The image on the left is obviously smaller, and that's because the width and the height is smaller. This one is affecting the actual size of the image. And then we have this view box property, which is defining the coordinate system, which has defined the canvas that we can draw on. And this one says in both cases that the coordinate system starts at 0, 0 in both cases, and the width and the height are 200, 200 each, which is not a pixel unit. This is an arbitrary unit that is used by the image element. So in both cases, these circles, think of the available space as a 200 by 200 unit wide and high canvas. And if we position this circle at 100, 100, then they're going to be at the center of the image, no matter how big the actual image is. All that matters for the image elements is the view box. Usually, this is aligned, so we have the same numbers in both cases, like in this case, we have 200 in both cases. But if it's not matching, then the image is just shrinked down or grown up. Now within this SVG view box, everything is positioned by coordinates.

3. Understanding Circle Element in SVG

Short description:

The circle element in SVG has a center position and a radius to define the size. By default, it is filled with black, but the fill color can be changed using CSS. The outline of the circle can be achieved using stroke and stroke width properties. Styling properties can be moved into CSS, but shape-defining properties like center position and radius cannot be moved.

As we see, the circle is having a center position. We don't have alignments like align left or grid or flexbox or the usual CSS alignments. We need to use coordinates.

Now the view box doesn't have to start at 0, 0. We can also start at any other number. So in this case, we start at minus 100, minus 100 and the width and the height is still 200. And in this case, the center of the image is going to be at 0, 0. And we don't even have to say that for the circle because that's the default.

Now after clarifying the view box, let's talk about the circle element in a bit more detail. The circle element is a very basic shape. It just has a center position as we saw and the radius to define the size. Now by default, as you see, this is going to be filled with a black color. If you want to change that, you can set the fill color. And here we set it to red, but we can set it to any other value that is valid in CSS for color values. So we can also use a hash color value. We can use the RGB function and so on.

Now if you don't want to fill this shape, but we want to have the outline of it, then we can use the stroke and the stroke width properties. This is pretty much similar to what we have in CSS for HTML elements like the border color and border width, but within SVG, we have to use the stroke properties. And we also have to say specifically that we don't want to fill this element because otherwise it's going to be black. Now what's cool about this, if we define this in HTML or in a React component, then we can move all the styling properties into CSS. Here we can set a class for the circle, for the circle itself, not the whole image, but specifically for each element. And then we can define the styling properties in CSS. We can only move the styling properties though. So we cannot move the properties that are actually defining the shape itself. So in case of a circle, we cannot move the center position and we cannot move the radius. Now this is true styling, these styling properties are true for any other shape as well. So we have the fill and the stroke, even if you have a path or a rectangle or a circle.

4. Understanding Rectangle Element in SVG

Short description:

The rectangle is another basic shape in SVG, defined by its top left position, width, and height. It is commonly used to create charts by mapping data points into rectangles. For more advanced charting, libraries like D3 can be used, which utilize SVG. However, SVG allows for custom creations as well.

So we have the fill and the stroke, even if you have a path or a rectangle or a circle.

Now let's look into another basic shape, which is a rectangle. This one is also very simple. Instead of having a center position, we have the top left position and then we have a width and we have a height and that's it. Now with this knowledge, we can already draw a basic chart. Here's a source code for a React component that is mapping some data points into rectangles. And here for each rectangle, we have to figure out the X and Y position and the width and the height based on the data points. And that's it. Of course, if you need some more advanced chart, then you're probably going to use the D3 library or some other charting library, which by the way, will most probably use SVG under the hood. But if you want to have something custom, you can actually do it yourself with SVGs.

5. Understanding Path Element in SVG

Short description:

Rectangles and circles are nice, but the path element in SVG offers more flexibility. It can be built from multiple path segments, including straight lines, curves, and arcs. Each path segment defines the end position, and the moveTo segment specifies the start position. The path can be non-continuous, and styling properties like stroke and strokeWidth can be applied. Transformations can also be used to define the shape's position, allowing for rotation and reuse of path elements.

Now rectangles and circles are nice, but if you're opening any SVG, then you're going to find a path element inside of it. And the path element is basically a freeform element, which we can build up from multiple path segments. We can have straight lines and curves and arc and so on. So let's try to break it down and see what's inside the definition of a path.

Here we have a simple line. And this line is already containing two separate segments. First we have a moveTo segment, and then we have a lineTo segment. Each segment always defines the end position, so the lineTo segment defines where does the line end, but it doesn't define where does it start. So that's why we have a previous segment with the moveTo that will describe where do we start things. So this one is basically a capital M, each segment always starts with a letter. Then we just have a coordinate, which says that we just move here, and from here, we draw a straight line here.

Now of course we can continue this, and we can just keep drawing straight lines to different coordinates. But what we can also do is instead of continuing this path, we can also just have another moveTo command and have a hamburger menu icon. So a path doesn't have to be continuous.

Now for styling, we use the same styling properties we had before. Here we don't have a fill property because this path is not surrounding any region. So even if you don't set the fill property, or if you would set it to any color, it wouldn't actually fill anything. But we set a stroke and strokeWidth to a relatively thick line, and then we also set this strokeLineCap property to have the ends of these lines rounded.

Now after talking about these basic path segments, let's talk about transformations. As I said before, every shape is defined by coordinates, and we could already draw this because we already know the circle element and we know how to draw a basic line, but we would need some trigonometry calculations to figure out this position, for instance. And instead of that, we can use transformations.

So we just start with a circle and then we have a simple line, which is just going from here to here. That's it. It has a moveTo and a lineTo segment. Then what we can do is we can assign an ID for it, and then we can reuse this path with the use element, which refers back to the path by ID, and it applies a transformation. So for each of these sun rays, we just move it, we just rotate it by 45 degrees. This way we don't have to figure out where does, where is this position actually or this position, we just keep rotating them. It's also important to note that this works in this case because the center of the coordinate system is in the middle of the image, so that's the zero, zero coordinate, because the view box is defined in a way that it starts at minus 15, minus 15, and it ends at 30, 30.

6. Using Transformations and Curves in SVG

Short description:

We don't have to figure out the position and can keep rotating the elements. The center of the coordinate system is the zero, zero coordinate. We can create more complex shapes, like the windmill, by grouping elements and applying transformations. We can animate the rotation using CSS keyframe animations. Curves, such as quadratic Bezier and cubic Bezier curves, add more interest to the shapes.

This way we don't have to figure out where does, where is this position actually or this position, we just keep rotating them. It's also important to note that this works in this case because the center of the coordinate system is in the middle of the image, so that's the zero, zero coordinate, because the view box is defined in a way that it starts at minus 15, minus 15, and it ends at 30, 30.

And by the way, the width and the height is just completely independent, even though the inner size is 30 by 30, the actual size is 200 by 200. Now with this logic, we can create other things like the windmill that we saw in the Gorilla's game. If you check the source code, we have a couple of things we haven't talked about before, so let's walk through the code of this one. At the bottom we have this path, which is the stand of the windmill. This is just a move to and a bunch of line to to draw this stand.

And now for the rest, we have the group element, which is grouping together the rest of the windmill. A group element is pretty much like a div element, so on its own it doesn't really do much. But if it would have some properties on it, like the fill property, then it will cascade down to the children. And in this case, as we are animating the whole thing, we can just animate this group instead of each children individually. Now within this group we have the circle, which is in the center. We have a path for one of these arms, which is built up from a move to and a couple line to segments. It also has this capital C segment, which is a cubic Bezier curve. As you see, this not only has one coordinate but a couple more parameters. We're going to talk about this in a bit. And then we are just reusing this arm with the use element and, again, apply transformation to have three different arms in three different directions instead of just having one.

Now what we can do here, and what we actually do here, is that we assign an ID for this group. And in CSS, we just define a keyframe animation where we just animate the rotate property, which earlier was part of translate. Now you can just use the rotate property on its own so it's not clashing with the translate, which was also part of transform before. So you can just set these values independently. And we have this little animation here. You can just use keyframe animations in CSS the way you would use with any other HTML element. We are also using the same technique when we are drawing this watch face, except here we are not using CSS to move the hands in position, but we are using JavaScript.

Now we covered a lot already. We covered some basic shapes, how to build up basic paths. But things are getting more interesting once you start using curves. So let's look into how a curve looks like. There are two kinds of curves. We have quadratic Bezier curves and cubic Bezier curves.

7. Quadratic Bezier Curve in SVG

Short description:

Quadratic Bezier curve starts with a capital Q. A control point determines the line's bend. The positions can be adjusted to bend the line in different directions.

This one is the simpler one. This is quadratic Bezier curve, starting with a capital Q letter here. But again, because path segments only define the endpoint, which is the last two numbers, we have to figure out where to start. So for that, before starting this cubic Bezier segment, we have another move to segment just to have a starting position.

Now after that, we have this cubic Bezier segment with the end position in the end. And before that, we have another position, which is called the control point. And this control point is defining how to bend the line. So if this would be between these two other points, then we have essentially a straight line and the more we move it away, the more the line is bending. And of course, we can bend it just in this direction or the other direction or the other way, like any way you want. And of course, these positions can also be anywhere you want.

8. Bezier Curves and More

Short description:

Quadratic Bezier curve allows for the bending of lines. Cubic Bezier curves smooth transitions between path segments, making them useful for complex shapes. Advanced features like drawing arcs are also available. For more examples and use cases, visit svgtutorial.com.

And now we have a quadratic Bezier curve. Now if you go back to the gorillas game we had before, the arm of this gorilla, and again, this is actually HTML canvas, but the parameters for curves is the same. So here we have a quadratic Bezier curve that starts somewhere around the shoulder, it ends around the hand, or it ends at the hand, and it has a control point which is somewhere around here. This is not an exact simulation, but what happens if I'm dragging this hand is that I'm only moving the endpoint. So as a result, I can have this very long arms and I have this arms bending the wrong way. But just by modifying one position out of these three, we already have a quite okay simulation. Now let's see if I'm lucky this time. Yay! Okay, I mean, I built this game, so I played a bit with it.

So after this, let's talk about the cubic Bezier curve, and this is a bit more advanced, but it's quite similar. So again, we start with a move to command, then with a capital C that we also saw in the windmill example, and the last two positions, or the last two numbers, which is a position, is the end position again. Before that, however, we have two other coordinates. We have a control point for the endpoint, and we have a control point for the starting point. And the way this works is this one essentially affects the start of the line. So it affects like how quickly does it turn and in what direction does it go initially. But it doesn't affect how the line ends. Like if you look at this part, that pretty much stays the same. Okay, it's moving a bit, but essentially it's only affecting the start of the curve and not the end of it. And then the other one, the other control point, is affecting the end of the line, so it affects like how quickly it turns and in what direction does it go first. So why is this useful? If you're building up more complex shapes, you often want to have a smooth transition between the different path segments. And what we have here is we have two straight lines. We have a straight line here and a straight line here. And then we're connecting these two segments with a cubic Bezier curve in a way that you wouldn't tell that we are changing segment here because the transition is smooth. The control points of this cubic Bezier curve are aligned with the previous and the following segment. Same story here, like we have a straight line here, we have a straight line here, and then we are connecting with a cubic Bezier in a way that the connection is smooth. So cubic Bezier curves are useful when you're building up more complex shapes and you want it to look like a nice shape.

Now this is pretty much what I want to talk about. So from this, you can already build up quite complex things. Of course, there are some more advanced things like you can also draw arcs that start with a capital A, and it also ends with an N position. The problem here is that it has like five other parameters, like different radiuses and angles, and you can go from the starting point to the end point in the long way or the short way or the other long way and so on. So this is a bit more advanced and I'm not going to get into it. If you're interested, then check out svgtutorial.com where you can find this whole presentation and a lot more small little examples and use cases that you can try out in your next project. So I hope this was useful for you and you learned something and got some inspiration for your following projects. I was Hunor. Please check out my website and see you on the web! Ciao!

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

The Whimsical Potential of JavaScript Frameworks
React Summit US 2023React Summit US 2023
28 min
The Whimsical Potential of JavaScript Frameworks
Top Content
Watch video: The Whimsical Potential of JavaScript Frameworks
The speaker discusses the whimsical and detailed work of Stripe, particularly their interactive and dynamic pages. They explain the use of React for building whimsical details and tracking mouse position. The speaker introduces React Spring for smooth animation and React3 Fiber for creating a 3D egg model. They also mention the use of Framer Motion and React server components for animating CSS properties.
Emotional & Functional UI Animations in React
React Day Berlin 2022React Day Berlin 2022
28 min
Emotional & Functional UI Animations in React
Today's Talk discussed the importance of UI animations in React, both functional and emotional. Examples were given using CSS and Framer Motion, with a focus on user feedback and accessibility. Design guidelines and animation usage were highlighted, as well as the consideration of negative emotions in animations. The Talk also touched on designing 404 error pages and concluded with gratitude to the audience and organizers.
React Native Animations Should Be Fun
React Advanced 2022React Advanced 2022
28 min
React Native Animations Should Be Fun
This talk is about animations in React Native, specifically focusing on React Native Reanimated. It covers the use of interpolations and extrapolations in animations, animating items in a carousel or list, sticky elements and interpolation, and fluidity and layout animations. The talk provides valuable tips and tricks for creating performant animations and explores the use of math formulas for natural movements.
Keep Scrolling
JSNation Live 2021JSNation Live 2021
33 min
Keep Scrolling
Scroll animations can enhance user experience when done properly, but should not distract from important information. CSS, JavaScript, and plugins like Scroll Trigger can be used to achieve scroll animations. GreenSock's ScrollTrigger provides a powerful JavaScript animation library for more complex animations. It is important to consider accessibility and provide reduced motion fallbacks. CodePen and GreenSock's documentation are valuable resources for learning and inspiration in creative coding.
Animation and Vue.js
Vue.js London Live 2021Vue.js London Live 2021
32 min
Animation and Vue.js
Today's Talk covers animation in Vue JS apps, including CSS animations, JavaScript animations using the GSAP library, and handling multiple elements with transition groups. The Talk also discusses different kinds of movements, state transitions, and animating numbers and SVGs. Overall, it provides a comprehensive overview of animation techniques and tools for enhancing Vue JS apps.
Animations with JS
JSNation 2022JSNation 2022
19 min
Animations with JS
Today's talk is about animations in Javascript, covering frame rates and different methods like CSS transitions and animations. JavaScript provides more control over animations, allowing interpolation and simulation of real-world scenarios. Different approaches to animating a box from zero to 100 pixels are discussed, including for loops, timers, and the web animations API. Request Animation Frame is highlighted as a solution for consistent and smooth animations. The Web Animations API is introduced as a powerful tool alongside CSS animations and transitions, although it has limited browser support.

Workshops on related topic

How to make amazing generative art with simple JavaScript code
JS GameDev Summit 2022JS GameDev Summit 2022
165 min
How to make amazing generative art with simple JavaScript code
Top Content
Workshop
Frank Force
Frank Force
Instead of manually drawing each image like traditional art, generative artists write programs that are capable of producing a variety of results. In this workshop you will learn how to create incredible generative art using only a web browser and text editor. Starting with basic concepts and building towards advanced theory, we will cover everything you need to know.