Main SVG elements


In the previous lesson, we learned about SVG: what it is, why it's great and even how to draw a little circle with it.

But to create comprehensive graphs, we'll also need other shapes such as rectangles, text, and lines. Let's explore how to create these as well.

Members only
6 minutes read

Rectangle

SVG rectangles are created using the <rect> element, which requires some attributes about position and size.

The x and y attributes specify the coordinates of the top-left corner, while width and height determine the size of the rectangle.

For example, this code will draw a blue rectangle with the top-left corner at (10,10) and dimensions of 80x50.

<rect x="10" y="10" width="80" height="50" fill="blue" />

Here is an interactive example so that you can experiment with rectangles and understand how they work.

Loading sandbox...

💡 In React, you can pass SVG attributes as numbers or strings. These three are all equivalent:

<rect x={4} />    // JS number
  <rect x="4" />    // HTML string
  <rect x={"4"} />  // JS string

You'll see all three styles in examples online. They all work the same — pick whichever feels most readable to you.

Line

SVG lines are created using the <line> element, which requires the starting (x1, y1) and ending (x2, y2) coordinates as attributes.

For example, this code will draw a black line from the point (0,0) to the point (100,100).

<line x1="0" y1="0" x2="100" y2="100" stroke="black"/>

Here is an interactive example so that you can play a bit with lines and understand how they work.

Loading sandbox...

⚠️ A line has no fill — it's just a stroke. If you forget the stroke attribute, nothing will appear! This is a common gotcha: unlike <rect> or <circle> which default to a black fill, a <line> needs an explicit stroke color to be visible.

Oh no! 😱

It seems like you haven't enrolled in the course yet!

This is a lesson from the D3 ❤️ React course, where you learn to create bespoke, interactive graphs with d3.js and React.

Enrollment is currently closed. Join the waitlist to be notified when doors reopen:

Or Login