Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback when DOM is loaded in react.js

Tags:

reactjs

I want to have a callback invoked on my react.js component when its DOM element (including all child nodes) is actually loaded on the page and ready. Specifically, I have two components that I want to render the same size, choosing the maximum of whichever component has the larger natural size.

It looks like componentDidMount is not really what I want because it is only called once per component, but I want my callback to be called again anytime the component is finished rendering. I thought I could add an onLoad event to the top level DOM element, but I guess that only applies for certain elements, like <body> and <img>.

like image 903
brianmearns Avatar asked Sep 26 '14 12:09

brianmearns


People also ask

How do you call a function when a page loads in React?

The useEffect runs by default after every render of the component. When placing useEffect in our component we tell React that we want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.

How do you check if page is loaded in React?

ReactDOM. render(<MyElement />, document. getElementById('root'), () => { console. log('page is loaded'); }) The function runs once the page is loaded.

How does React handle DOM?

React uses virtual DOM to enhance its performance. It uses the observable to detect state and prop changes. React uses an efficient diff algorithm to compare the versions of virtual DOM. It then makes sure that batched updates are sent to the real DOM for repainting or re-rendering of the UI.

How do you access the DOM element in React?

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.


1 Answers

Add onload listener in componentDidMount

class Comp1 extends React.Component {  constructor(props) {     super(props);     this.handleLoad = this.handleLoad.bind(this);  }   componentDidMount() {     window.addEventListener('load', this.handleLoad);  }   componentWillUnmount() {     window.removeEventListener('load', this.handleLoad)    }   handleLoad() {   $("myclass") //  $ is available here  } } 
like image 70
John Avatar answered Sep 20 '22 10:09

John