Home
Basics
Introduction Setting up environment First Component JSX Component lifecycle Class Based Components Function Based Components Props State Hooks useState hook useEffect hook Events Server requests CSS in React Router third party JavaScriptAdvanced
useContext hook useRef hook useReducer hook Memo useCallback hook Custom Hooks React and ReduxMiscellaneous
React Third Party Components Html templates in React React Interview QnAExternal JS in react
External JS can be imported using 4 ways.- Install NPM package for JS lib and import it in a component that needs it
- Using script tag in index.html - not good way because it will load everytime
- Using react-script-tag package
- Using react-helmet package
- Dynamically creating script tag
import { useEffect } from 'react';
const loadScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, [url]);
};
export default loadScript;
// Now we can use this custom hook in the components that need dynamic script
// Ideally we should check if external JS is available in NPM registry and use that.
import loadScript from 'customHooks/loadScript';
const Component1 = props => {
loadScript('https://code.jquery.com/jquery-3.6.1.min.js');
}
const Component2 = props => {
loadScript('https://code.jquery.com/jquery-3.6.1.min.js');
}
Web development and Automation testing
solutions delivered!!