Here's an application running on create-react-app
and Next JS
. Difference between them is CRA seems to have loaded bootstrap.mon.js and jquery.min.js while NextJS has not. I added a HEAD section to NextJS code through next/head and attempted to load both JS files. Although there were no errors, I did not see right results either.
Can someone help me understand why this happens with NextJS and what should I do to get NextJS load my application right with bootstrap and jquery
-
Code for CRA - github.com/KrishnanSriram/cra Code for NextJS - github.com/KrishnanSriram/nextjsKrishnan Sriram– Krishnan Sriram2019-09-20 17:25:24 +00:00Commented Sep 20, 2019 at 17:25
-
Please let me know if you find a solution for thisYorkshireman– Yorkshireman2019-12-02 22:16:43 +00:00Commented Dec 2, 2019 at 22:16
Add a comment
|
4 Answers
Add this snippet to your _app.js just above your return code
useEffect(() => {
import("bootstrap/dist/js/bootstrap");
}, []);
so your complete _app.js will be like this
import { useEffect } from 'react';
function MyApp({ Component, pageProps }: AppProps) {
useEffect(() => {
import("bootstrap/dist/js/bootstrap");
}, []);
return <Component {...pageProps} />
}
export default MyApp
1 Comment
afikri
not working for me, as it says Module not found: Can't resolve 'js/whatevermyjsis.js'
You can require client-side libraries in componentDidMount() after installed via npm.
import React, { Component } from 'react';
export class HomePage extends Component {
render() {
return (
<div>
Hello
</div>
);
}
componentDidMount() {
require('jquery');
require('popper');
require('bootstrap');
}
}
export default HomePage;
Comments
Use defer attribute in bootstrap Script tag , that will help first load jquery then load bootstrap
<Script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" strategy="afterInteractive" ></Script>
<Script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossOrigin="anonymous" strategy="lazyOnload" defer/>