In this article, we will learn how to load custom JS and CSS files on a component and Create Element (Script or Link) using React.js.
Sometimes it will be used to add CSS or JS files in index.html for the particular component.
Let’s Begin.
Custom CSS file load on component
const cssFile = document.createElement("link"); cssFile.href = "/dist/css/dashboard.min.css";// your css file path cssFile.rel = "stylesheet"; document.head.appendChild(cssFile);
Custom JS file load on Component
const scriptFile = document.createElement("script"); scriptFile .src = "/dist/js/pages/dashboard.min.js";//your js file path //scriptFile .async = true; document.body.appendChild(scriptFile);
Apply in Dashboard.js using class component
export default class Dashboard extends Component { componentDidMount() { const cssFile = document.createElement("link"); cssFile.href = "/dist/css/dashboard.min.css";// your css file path cssFile.rel = "stylesheet"; document.head.appendChild(cssFile); const scriptFile = document.createElement("script"); scriptFile .src = "/dist/js/pages/dashboard.min.js"; //your js file path //scriptFile .async = true; document.body.appendChild(scriptFile); } render() { return ( <div> <h4>Dashboard</h4> </div> ) } }
Apply In Dashboard.js using functional component
const Dashboard = () => { useEffect(() => { const cssFile = document.createElement("link"); cssFile.href = "/dist/css/dashboard.min.css";// your css file path cssFile.rel = "stylesheet"; document.head.appendChild(cssFile); const scriptFile = document.createElement("script"); scriptFile.src = "/dist/js/pages/dashboard.min.js"; //your js file path //scriptFile .async = true; document.body.appendChild(scriptFile); }) } export default Dashboard;
If you have any questions about this article, please let me know.
You can check my previous blog here.
Thank you.
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular