How to Code Images in React with SVG

Rate this content
Bookmark

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.

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

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.

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.

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.

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.

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
WorkshopFree
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.