I’m trying to include external script files in my React project to use them in various parts of my code. I’ve created a ScriptLoader component to handle the loading of these script files, but I’m encountering an “Unexpected token ‘<‘” error. How can I properly add external script files to my React project and avoid this error?
this is App.jsx
var scripts = [
"./rooteFile/assets/js/jquery.min.js",
"./rooteFile/assets/js/bootstrap.min.js",
"./rooteFile/assets/js/waves.js",
"./rooteFile/assets/js/wow.min.js",
"./rooteFile/assets/js/jquery.nicescroll.js",
"./rooteFile/assets/js/jquery.scrollTo.min.js",
...
];
function App() {
return (
<>
<Layout>
<ScriptLoader scripts={scripts} />
<Index />
</Layout>
</>
);
}
export default App;
and my components
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.async = true;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
const ScriptLoader = ({ scripts }) => {
useEffect(() => {
scripts.reduce((prev, src) => {
return prev.then(() => loadScript(src));
}, Promise.resolve());
}, [scripts]);
return null;
};
export default ScriptLoader;
You can write:
“I attempted to add external script files to my React project using a ScriptLoader
component. I expected the scripts to be loaded without errors, but I encountered an “Unexpected token ‘<‘” error in the browser console. I tried including the script paths in an array and passing it to the ScriptLoader
component in my App
component, but the error persisted. What steps can I take to resolve this issue and successfully load the external scripts in my React project?”