Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customise cursor pointer using a react component

I'm trying to customize the cursor pointer so I used a hook to get the mouse position and then I placed the component in absolute in that coordinates.

Here a working code.

There is a flag (USE_PNG) that you can toggle to test if to use a React component or a png (I would prefer the first idea but I'm interested also to the second one if it has some advantages).

  • USE_PNG = false -> use a React component

    As you can see, the code is very simple and it works enough but it has some problems:

    1. when the mouse is on the left side of the window, the left half of the cursor is cut off, but when is on the right then it's not and the horizontal bar appears
    2. it seems not so fluid. Are there some tricks I can use to optimize the code?
  • USE_PNG = true -> use a png

    I tried also to use a png (simpler maybe) but I can't see the cursor anymore

What's the problem?


I use a ref instead of a state and performance have improved. The first problem remains: the horizontal and vertical scroll when the cursor is on the right or bottom side of the window

enter image description here


I don't think simply hiding the scrollbars is an optimal solution because the window size has changed and the user can scroll. I think we need to find a cleaner solution.

enter image description here

like image 824
marielle Avatar asked Oct 19 '25 02:10

marielle


1 Answers

Edit - Overflowing body (AKA third problem)

if you'll add this to your body tag it should solve it:

  margin: 0;
  height: 100%;
  overflow: hidden

edit - Regarding your second problem

to prevent scroll bars to appear, you can use overflow-y: hidden; (to disable on the x-axis just change the overflow-y to overflow-x, overflow: hidden; for both)

BUT if you would like to enable scrolling but just hide the scrollbar, use the following code:

/* hide scrollbar but allow scrolling */
body {
  -ms-overflow-style: none; /* for Internet Explorer, Edge */
  scrollbar-width: none; /* for Firefox */
  overflow-y: scroll; 
}

body::-webkit-scrollbar {
  display: none; /* for Chrome, Safari, and Opera */
}

here is a gif of a working example on my browser: https://i.sstatic.net/q7gtO.jpg


It doesn't get cut off for me on the right side (see image below). It sounds like the second problem happens because your cursor gets re-rendered every time you move it, and that's a ton of work for your site!

you should remove the style attributes from the Cursor component and adjust the code inside your event listener for a mousemove event. it will look like this:

onMouseMove = {e => {
    const cursor = document.querySelector('.cursor')
    cursor.style.top = ׳${e.pageY}px׳
    cursor.style.left = ׳${e.pageX}px׳
}}

not getting cut off

like image 60
Guy Nachshon Avatar answered Oct 21 '25 16:10

Guy Nachshon