Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use document.getElementById() with styled components in react?

I want to use JS functions like document.getElementById() in my react project. I am new to styled components and don't know how to use these functions with them. Do not refer to the official 'styled-components' page, I have already seen it.

like image 429
Sandeep Avatar asked Apr 22 '26 21:04

Sandeep


2 Answers

You can use useRef react Hook for this.

const reqElement = React.useRef(null);

Now, you can add ref={reqElement} in your required element.

After that you can use reqElement.current to do those things that you can do via document.getElementById() in javaScript.

useRef hook refrence

like image 58
Dibas Dauliya Avatar answered Apr 25 '26 10:04

Dibas Dauliya


I have finally found an answer to my question here. I laying down the gathered information in the following points.

  1. Styled Components does have an id parameter but we must not use it in react for DOM functionalities as the main motive behind react is to prevent frequent changes in the real DOM.
  2. We can use useRef() hook in React functional components for passing references in react. (Look at Dibas's answer above.)
  3. I was making a mistake of not using useState() hook to store the state of the component, instead I used an identifier, which is wrong as useState helps to re render the component whenever the state changes.
  4. Use a cleaning function in useEffect() hook to prevent memory leak.

Here is a link to a Parallax effect video https://youtu.be/Q5y6pwoE3cM hope this can help you.

like image 23
Sandeep Avatar answered Apr 25 '26 12:04

Sandeep