Reputation: 157
I am a beginner to React and working on a project. For this, I bought a template online which is suitable for my requirement. But that project is not in react. So, I convert that project to the React components. But, I am confused about how to include custom javascript files. These custom JS files have their own functions. For example, I have a sidebar in HTML, I convert that sidebar file from HTML to react component. Then, I include the CSS and bootstrap files. Like this.
import 'bootstrap/dist/css/bootstrap.css';
But, How to include the custom javascript file. The template downloaded by me has its javascript files having their functions. So, if i include those files in my react project, still the react file gives an error.
Module not found: Can't resolve './components/Sidebar' in '/app/src'
because the sidebar file uses a function that is inside the custom js file. Is there a way to add a custom JS file in react and if yes then how to use the functions that are inside that custom js file in your React app?
Please guide me regarding this. Any help would be appreciated.
Upvotes: 1
Views: 930
Reputation: 4623
I think you should try to import the whole js
file (with an extension).
But anyway, the simplest way to append an external vanilla js file to your document (I think) is to do it in useEffect
, like so:
useEffect(() => {
const script = document.createElement('script');
script.src = "/app/src/components/Sidebar.js";
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
Upvotes: 1