19

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?

2
  • 1
    i guess you can use com1.promise().done(fn).
    – Jai
    Mar 20, 2015 at 12:49
  • 1
    Sorry could you elaborate please, I'm new to reactjs and am now sure what you mean. Where would I put this code for example and I assume "fn" could take any javascript (e.g. alert("test"))?
    – p_mcp
    Mar 20, 2015 at 13:01

2 Answers 2

44

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

1
  • From my own experience - you also need to add a setTimeout(foo, 1) method inside the 'componentDidMount', so that the elements that react renders actually show in the real dom. Jun 16, 2022 at 14:53
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.