Search code examples
htmlcssreactjssvgcursor

Using an image URL for the DOM style cursor property


I am trying to use a custom cursor icon under certain conditions in my React application.
Assuming that the following works as expected:

this.element.style.cursor = 'crosshair'

How can I use an .svg image instead of one of the native cursor values?

Syntax that hasn't worked:

this.element.style.cursor = '../relative/path/icon.svg'
this.element.style.cursor = ['../relative/path/icon.svg']
this.element.style.addProperty('cursor', '../relative/path/icon.svg', 'auto')

Its probably either a simple path or syntax issue, but any insight is greatly appreciated.


Solution

  • The syntax of the string needs to be in url() format:

    this.element.style.cursor = 'url(../relative/path/icon.svg), pointer';
    

    In React you might need a template literal to evaluate the path:

    this.element.style.cursor = `url(${myURLVarialble}), pointer`;
    

    You can also define the custom cursor in a CSS class and apply the class to the element.