Is it possible to adjust the element's position using the code "element.style.top = window.scrollY"?

Recently, I attempted to create a floating input element that would follow the scroll. After much effort, I managed to achieve it and the code is provided below.

However, I encountered an issue when trying to change "setText(window.scrollY)" to "document.querySelector(".code).style.top = window.scrollY". Surprisingly, the latter doesn't yield the same result even though I believe it's essentially the same code. Can someone shed light on why this might be happening? Thank you.

import React, { useState } from "react";

function Input() {
  const [scroll, setScroll] = useState(0);
  
  window.addEventListener(
    "scroll",
    function () {
      if (typeof document.querySelector(".code") === "undefined") {
        alert("TT");
      } else {
        setScroll(window.scrollY);              // *this part
      }
    },
    { passive: true }
  );

  return (
    <input
      style={{
        top: text
      }}
      className="code"
      autoComplete="on"
      placeholder="Write code please"
    />
  );
}

export default Input;

Answer №1

 updateScrollPosition(window.scrollY+"px");  

Answer №2

For improved efficiency, opt for the useRef() hook over utilizing

document.querySelector(".code")
. React operates with a virtual DOM, so calling
document.querySelector(".code")
may not yield access to the real DOM yet. Utilize useRef instead to target the virtual DOM and execute your alterations on it by using the ref's .current property.

Additionally, encase the scroll event handler within React's useEffect hook to ensure proper attachment when the component mounts.

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

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Error: Unable to assign value 'auto' to property of null object

Whenever I attempt to update my MongoDB using AngularJS on the front end and Node.js on the backend, I encounter a `TypeError: Cannot set property 'auto' of null error. Here is the code snippet that resulted in this issue: AngularJS Code: scope ...

Having difficulty sending emails with Nodemailer

This is a simple example showcasing the usage of Nodemailer library. var http = require('http'); var port = process.env.PORT || 8080; var async = require('async'); var nodemailer = require('nodemailer'); // Creating a transp ...

Ensuring validation with Javascript upon submitting a form

Hey there, I'm looking to validate field values before submitting a form. Here's the code I have: <table width="600" border="0" align="left"> <tr> <script type="text/javascript"> function previewPrint() { var RegNumber = docum ...

Is it possible to utilize the cv.imencode function in Opencv.js for exporting images in the webp format?

I'm looking to convert images from various extensions like png and jpg to webp format. I initially explored using OpenCV.js but was unable to locate the cv.imencode method for creating webp images. Can anyone confirm if this method is supported? If no ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...

Is it possible to align a clip-path starting from the right edge?

On my webpage, I have a unique hamburger icon that is positioned 2rem away from the right and top edges. I am looking for a convenient way to create a clip path that grows from its center point. Calculating the center point is not difficult but unfortunate ...

The resolution of the images in jspdf is unsatisfactorily low

Hello there! I've been working on a ReactJs project and using the jsPDF package to generate PDFs. However, I've been facing an issue with image quality when adding images to the PDF. I've checked the base64 code for the image and it seems f ...

Looking for a way to merge PDF files using an API?

I'm working on a web application that allows users to upload PDF files. I'm trying to find a way to add an additional PDF to the one uploaded by the user, but I haven't been able to solve this task yet. I'm wondering if there's an ...

What could be causing the information from the ajax call to not appear in this popover?

Hovering over a link will trigger a popover with a 1 second delay containing user profile information, loaded using AJAX. $(function() { var timer = null; var xhr = null; $('.user_popup').hover( function(event) { ...

Retrieving URL Parameters in Next.js Version 13

Currently, I am in the process of developing a Next.js 13 project with a dedicated /app directory. One issue that has arisen involves the creation of a fixed navbar component within the root layout. This navbar component is imported from /components/Navb ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

The CSS linear gradients rainbow wheel is missing a few sections, only displaying part of its 12

I've almost got everything working, but I'm facing a challenge in displaying all 12 sections of the rainbow wheel. I know it's probably something very simple (Occam's razor). I've been following this amazing tutorial on CSS linear ...

Tips on modifying webpage content based on page size (zoom) in responsive web design using CSS

I have a good understanding of responsive design and how to set elements with relative width. My specific question is regarding the transition of the page from thisto that. Any insight on this would be greatly appreciated. Thank you in advance. ...

Error 404: Page not found. Sorry, we couldn't locate the Node JS and Express resource

I have been trying to access the routes /api and /api/superheroes, but I keep encountering an error message whenever I try. Not Found 404 NotFoundError: Not Found at C:\Users\mikae\Desktop\Project\node-express-swig-mongo\a ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

After filtering the array in JavaScript, perform an additional process as a second step

My task involves manipulating an array through two methods in sequence: Filter the array Then, sort it The filter method I am using is as follows: filterArray(list){ return list.filter(item => !this.myCondition(item)); } The sort method I a ...

The main attribute in the NPM package.json is missing or has no appropriate entry

I'm really struggling to figure out the best approach for setting up my package.json file. I have a JavaScript module that contains multiple reusable JS files, let's call it Module1. In Module1's package.json, the name attribute is set to " ...

Steps for making a toggle button with Bootstrap

Initially, I developed a web application using HTML, CSS, and JavaScript. Later on, I was requested to recreate it using Bootstrap as well. While I managed to complete the task successfully, I encountered an issue where toggle buttons in the web app revert ...

Experience the visually stunning React Charts line chart featuring grouped labels such as months and weeks

Can you create a line chart in recharts with grouped points, such as displaying 6 months data series per day for about 180 days? Each point on the chart represents a day, but I want the X-axis labels to show the corresponding month like Jan, Feb, Mar, Apr, ...