Render Basic SVG Components in React

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

React loves svg just as much as it loves html. In this lesson we cover how simple it is to make SVG components in ReactJS.

Creating SVG components with React allows you to inline SVG. Inline SVG has an advantage that it can be styled with CSS just like the rest of your webpage and doesn't need a separate web request to load.

An additional advantage is of-course that you can use component props to customize the contents of the SVG.

[00:00] Here, I have a simple HTML page with a div ID root where I am rendering this app component, which simply renders out the text demo. If I go ahead and change it to "Hello World," you can see that the page updates.

[00:20] We are going to replace the HTML in the component with SVG. Here, I have a simple SVG file that renders an "I." If I go ahead and view its source, I can select all of it and copy it to the clipboard.

[00:35] I am going to replace the div with the contents of the SVG file. You can see that I get a few errors. In this case, it is a matter of moving the XML link spaces, as those are no longer required. As soon as I do that, you can see that the SVG gets rendered by React.

[00:55] With React, we can easily customize the contents of the SVG. For example, I can customize the width using a size property which I am going to default to the previous value. I am also going to use the size for height and for width.

[01:19] You can see the component still renders the same, but now I can provide a different size property, for example 100 pixels, and the component renders a bit bigger.

egghead
egghead
~ 5 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today