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?
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.
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.
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.
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.
Use componentDidMount method to run code after initial render and componentDidUpdate to run code after each update of component's state.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With