Home > Enterprise >  how to use getElementById in .js which tag is in .ts?
how to use getElementById in .js which tag is in .ts?

Time:08-07

Am trying to use electron, preload, renderer with reactj and typescript.

<index.html>

<body>
<div id="root" />
<script src='./renderer.js'/>
</body>

<index.ts>

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(<App />);

<App.ts>

<div className="App">
    <header></header>
      <MainPage />
  </div>

<MainPage.ts>

<div>
  <btn id='load' />
</div>

<renderer.js>

console.log(document) ----------------------------> OK
console.log(document.getElementById('root')) ------> OK
console.log(document.getElementById('load')) ------> null

To use id='load' btn in renderer.js, what can I do? what am I missing??

CodePudding user response:

You need to wait until the component mounted, you can use it inside useEffect hook.

useEffect(() => {
  console.log(document.getElementById('load'))
}, [])

Or you can use template ref.

ts:

import { useRef } from 'react'

const buttonRef = useRef()

useEffect(() => {
  console.log(buttonRef.current)
}, [])

html: Button

CodePudding user response:

As you can see, there is only an empty div in your html file. When index.ts file is executed, React DOM renders and displays the React code you have in App.ts. It means React DOM updates the DOM to match your React elements.

If you run console.log(document.getElementById('load')), before React DOM has finished the initial render of MainPage component, there is no <btn id='load' /> element in your html file. Hence console logs null.

You should wait for React DOM to render the btn. After MainPage component is mounted (meaning is added to html file), you can access the btn by using document.getElementById('load').

To make sure your code is executed after btn with id='load' is mounted:

  • Using React Functional components: call the function you want inside useEffect with an empty array of dependencies. Read more
  • Using React Class Components: use componentDidMount method. Read more
  • Using Javascript: If you do not want want your code to be called inside React, use MutationObserver API. Read more
  • Related