7

Here's an application running on create-react-app enter image description hereand Next JS enter image description here. 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

2

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

not working for me, as it says Module not found: Can't resolve 'js/whatevermyjsis.js'
1

You have to require the modules at the client-side. so you can use this

// _app.js

if (typeof window !== "undefined") {
  require("jquery");
  require("popper.js");
  require("bootstrap/dist/js/bootstrap");
}

Comments

0

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

0

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/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.