Categories: React

How To Load Custom JS And CSS File On Component Using React.js

Introduction

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.

Sagar Rana

Sagar Rana is a Web Developer in Vision Infotech. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, .Net Core, Jquery, JavaScript, WEB API, React.js, ADO.Net, Entity Framework, SQL and different integration like Xero, Stripe, Zoho CRM, Square, PayTM, PayKUN, RazorPay, Quickbook Desktop etc.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago