Guide on using an image as a background in a <svg> element with React.js

I am facing an issue with filling an SVG path with a background image. I have tried various methods found on Google, but none seem to work as expected. Here is the code snippet I have been working with:

      <div className="intro">
          <p>Any text</p>
              <svg fill="url(#pattern)">
                  <defs>
                      <pattern id="pattern">
                          <image href={introImage}/>
                      </pattern>
                  </defs>
                  <path d={path()}/>
              </svg>
      </div>

Despite following this setup, the SVG still doesn't display the background image. Interestingly, setting fill="red" works perfectly fine.

After thorough inspection, I believe the issue might be related to React and its handling of SVG elements. The image link and the "d" attribute of the path are indeed correct, so my question is how can I resolve this dilemma?

Answer №1

Looks like you're just missing a few attributes in your <svg>, specifically:

          <svg xmlns="/#pattern">
            <defs>
              <pattern
                id="pattern"
                patternUnits="userSpaceOnUse"
                width="1200"
                height="600"
              >                             {/* <---- these attributes needed here */}
                <image
                  href="https://api.time.com/wp-content/uploads/2018/05/forest-bathing.jpg?quality=85&w=1200&h=628&crop=1"
                  height={600}
                  width={1200}
                  x={0}
                  y={0}
                />
              </pattern>
            </defs>
            <path
              d="M0,214.7L282,0h433v399.5l-75.5,97.7l-224.2-49L308.4,557l-180.7-26.3L0,214.7z"
              fill="url(#pattern)"
            />   {/* ^---- fill your object with your image via class reference here! */}
          </svg>

Check out this CodeSandbox Example for reference: https://codesandbox.io/s/stack-custom-svg-path-w85cu?file=/src/App.js


If you encounter similar issues, you can also refer to the following resources:


Isn't it funny how sometimes you search for an answer online, only to find a solution you posted yourself in the past!

Remember,

patternUnits="userSpaceOnUse"
is ideal for patterns with a large object and smaller repeating image. If you want to fit an image to an object, consider using
patternUnits="objectBoundingBox"
. For more information, check out:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the image URL to not function properly in the CSS file?

I have been struggling with this issue all day and have searched numerous sources for answers. The login.css file can be found at: WebContent/resources/css/login.css The image file is located here: WebContent/resources/img/pencil.jpg Despite my attem ...

Error in Typescript for the prop types of a stateless React component

When reviewing my project, I came across the following lines of code that are causing a Typescript error: export const MaskedField = asField(({ fieldState, fieldApi, ...props }) => { const {value} = fieldState; const {setValue, set ...

Is there a way to customize the scrollbar color based on the user's preference?

Instead of hardcoding the scrollbar color to red, I want to change it based on a color variable provided by the user. I believe there are two possible solutions to this issue: Is it possible to assign a variable to line 15 instead of a specific color lik ...

What is the method for storing elements in localStorage within a ReactJs application?

Currently, I am working on learning react-redux and coding a new project. My goal is to implement a feature where clicking the Add Favorites button will push all column data to local storage. Despite reading numerous articles, none of them have provided ...

What is the process for triggering an unordered list when I click on a table data cell within the Hospitals category?

Hi there! I need help with writing a JavaScript function for Hospitals in the code below. When I click on Hospitals, I want to display the values in the unordered list. Expected output: Hospitals--->onclick Bangalore| salem |Goa| Mangalore| Visakhapat ...

Using Node.js server along with MySQL database and socket.io technology for real-time

I need assistance in creating a Node.js server that integrates with MySQL and socket.io. Can someone please provide me with some sample code? Our database table consists of 20 columns, and every 30 seconds we receive new data through various operations s ...

What strategies can be used to identify and react to both success and failure outcomes from a component within Flux architecture?

Consider this scenario: a user initiates the creation of a resource by clicking on the "create" button, triggering an action to send data to the API. Upon successful creation of the resource, a "Success" action is dispatched; in case of failure, a "Failure ...

Access and retrieve data from a string using XPath with JavaScript

My HTML page content is stored as a string shown below: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </ ...

The height of the href is not displaying correctly when the text-decoration is disabled and it is placed next to

In my design, I have a link positioned next to an image with perfect vertical alignment. Everything looks great when the text has the standard text-decoration, centered vertically and all that. However, as soon as I remove the text-decoration, leaving the ...

Is it not possible to make updates while the state is already in transition?

this.state = { filterData: [{ attribute: '-1', filter: '-1', value: '' }], } _createFilterUI(dataSourceColumns) { if (this.state.dataSourceIndex == -1) return <div > Kindly first select Data Sourc ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

Need at least one form input field out of three to be completed

Currently, I am developing a database program where users are required to enter some of their contact information. <form action="add_action.php" method="POST"> <div class="modal-body"> Name: <br> ...

MatDialog displaying no content

I found this tutorial on how to implement a simple dialog. The issue I'm facing is that the dialog appears empty with no errors in the console. Even after making changes to my dialog.component.html or dress-form.ts, nothing seems to reflect in the o ...

Material-UI Scroll Dialog that begins scrolling from the bottom

While attempting to incorporate a scrolling div with the ref tag inside Dialog Material-UI Design, I encountered an error stating Cannot read property 'scrollHeight' of undefined When running my code outside of the Dialog, it functions correctly ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Ensuring WCAG Accessibility Compliance - mandate the inclusion of at least one input in a fieldset

I'm working on a form where users need to provide at least one contact method from a group of fields, such as home, work, or mobile phone number. How can I ensure this meets the latest WCAG 2.2 standards? <!-- Other fields above and below --> ...

Equivalent of ResolveUrl for loading scripts without the need for server technology

I am in the process of converting an ASP.NET web page into a plain HTML web page. Most of the work is done, however, I am having trouble replacing the ASP.NET Page.ResolveUrl function when setting a reference to a javascript file: <script src="<%= ...

Using a vanilla JS object as a prop for a child component

I have created a custom Message class in my application to handle incoming messages, which is defined in message.js. Within message.js, I've implemented two classes: Message and EventEmit. The render function in my Message class requires passing an E ...

By setting up a keydown event listener, I am unable to inspect HTML elements by using the F-12 key shortcut in Chrome

Recently, I encountered an issue where adding a keydown event listener in my JavaScript code prevented F-12 from working properly. window.addEventListener("keydown", function (event) { if (event.defaultPrevented){ retu ...

Tips for adjusting website display height on mobile devices

My desktop website appears exactly as I want it to. When inspecting the site on the console to test responsiveness, everything seems fine. However, once I upload the changes to AWS and view the website on my phone, the vh and flexbox properties are not fun ...