Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript after reactjs render method has completed

I have a reactjs component:

var com1 = React.createClass({
    render: function() {
        return (  
    <a href='#'>This is a text</a>
    );
  }
});

I want to execute Javascript/Jquery once rendering of this componenet has completed. Simply adding Javascript to the render method doesn't seem to work.

How would I achieve this?

like image 746
p_mcp Avatar asked Mar 20 '15 12:03

p_mcp


People also ask

Which method called after render in React?

Need to run some code after a React component renders? Maybe you're familiar with componentDidUpdate and you're looking for the equivalent hook… Well look no further… the answer is the useEffect hook.

How do you call JavaScript function from React?

First, create a React project by typing inside the terminal. To execute a external JavaScript function, we need to put the name of the function “alertHello” inside the square bracket. If you click on the alert button, it should popup the alert “Hello”. This imply we can call the external JavaScript function from React.

How do I run JavaScript in JSX?

To add JavaScript code inside JSX, we need to write it in curly brackets like this: const App = () => { const number = 10; return ( <div> <p>Number: {number}</p> </div> ); }; Here's a Code Sandbox Demo. Inside the curly brackets we can only write an expression that evaluates to some value.

Does useEffect run after render?

The useEffect Hook Usages. The callback function we pass to the useEffect hook runs the side effects. React runs it on every render of a component by default.


2 Answers

Use componentDidMount method to run code after initial render and componentDidUpdate to run code after each update of component's state.

like image 63
Roman Liutikov Avatar answered Oct 11 '22 12:10

Roman Liutikov


See the documentation here: https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

In the component lifecycle, you can define a callback for componentDidMount -- i.e., the render function has completed and the resulting elements have been inserted into the DOM.

like image 36
kakigoori Avatar answered Oct 11 '22 14:10

kakigoori