How to use SVG in React

Table of Contents

Introduction

In React, we often use SVG for icons or images. How do we use it efficiently? How do we add a number in the centre of a trolley icon? We will figure our how to achieve those things in a minute.

A Real Case

The shopping cart icon is rendered at the top right of the menu bar where it shows the items buyers have added in. The piece of HTML codes below will render the trolley cart and 10 in the middle of the trolley which is an example of the quantity added by buyers.

<h1 class='cart'>
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" id="IconChangeColor"
       height="68" width="68">
     <rect width="156" height="156" fill="none"></rect>
     <circle cx="80" cy="216" r="12"></circle>
     <circle cx="184" cy="216" r="12"></circle>
     <path
       d="M42.3,72H221.7l-26.4,92.4A15.9,15.9,0,0,1,179.9,176H84.1a15.9,15.9,0,0,1-15.4-11.6L32.5,37.8A8,8,0,0,0,24.8,32H8"
       fill="none" stroke="#faf9f9" stroke-linecap="round" stroke-linejoin="round"
       stroke-width="2" id="mainIconPathAttribute"></path>
     <text text-anchor="middle" x="50%" y="50%" dy=".35em" font-family="sans-serif" font-size="90px" fill="white">10</text>
  </svg>
</h1>

Thanks to the question here, we found another example using SVG and inserting a number inside it. In practice, the number is automatically rendered depending on how many quantities buyers add to their shopping cart.

<h1>
<svg width='128' height='64' viewBox='0 0 128 128' xmlns='http://www.w3.org/2000/svg' version='1.1' >
  <circle cx="64" cy="64" r="62" fill="rgb(0,100,0)" stroke="red" stroke-width="2"/>
  <text text-anchor="middle" x="50%" y="50%" dy=".35em" font-family="sans-serif" font-size="90px" fill="white">20</text>
</svg>
</h1>

Hopefully, this helps your life.

References

[1] https://www.telerik.com/blogs/how-to-use-svg-react, accessed on 13 Oct 2024

[2] https://www.freecodecamp.org/news/how-to-use-svg-icons-in-react-with-react-icons-and-font-awesome/, accessed on 13 Oct 2024

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur la façon dont les données de vos commentaires sont traitées.