SimpleNext.js

How to use Bootstrap 5 with Next.js

Cover Image for How to use Bootstrap 5 with Next.js
Marouane Reda
Marouane Reda
If you need to understand the basics of Next.js, i recommend this course. (Disclaimer : this is an affiliate link that may earn me a small commission, but with no extra cost to you if you choose to enroll)

Along with ant design and chakra-ui, Bootstrap is the most widely used componenet library that you can use to speed up the developpement of your next.js app, giving it a nice professional feel.

how to setup Bootstrap 5

  1. Open your terminal window and navigate to the place you want your Next.js project to locate in then running:
npx create-next-app next_bootstrap

The name is totally up to you.

  1. Navigate to the project root folder:
cd next_bootstrap
  1. Install Bootstrap 5 set with the following command:
npm install bootstrap@next
#or
yarn add bootstrap@next
  1. Manually import the bootstrap.css file at the very top of your pages/_app.js file:
import 'bootstrap/dist/css/bootstrap.css'

Now, we’re ready to use Bootstrap components in our Next.js app. For example, we will modify our pages/index.js to add a normal button, a ghost button and a date picker :

export default function Home() {
  const onChange = () => {};
  return (
    <div style={{ padding: 100 }}>
      
        <Button type="primary">Primary Button</Button>
       
     
    </div>
  );
}

this is the result :

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-07-07%20a%CC%80%2020.20.59.png?alt=media&token=768c5bc2-1341-41d5-88b3-35b4480dcddf

See the difference without bootstrap :

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-07-07%20a%CC%80%2020.21.20.png?alt=media&token=3c36886e-9c2c-4b96-9574-67c0aeb05a7a

  1. Manually import bootstrap's javascript file in your pages/_app.js file:

With the previous steps, the components that need bootsrap's Javascript (like dropdown, carousel, ...) won"t work even if you import bootstap's javascript file in the top of _app.js.

What we should do is import the file via the useEffect hook : the _app.js file will look like :

import 'bootstrap/dist/css/bootstrap.css'
import '../styles/globals.css'
import { useEffect } from "react";

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    import("bootstrap/dist/js/bootstrap");
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp




Now our components will work normally, exemple a dropdown menu :

export default function Home() {
  return (
    <div className="container p-3">
      
     

      <div className="dropdown m-3">
        <button
          className="btn btn-secondary dropdown-toggle"
          type="button"
          data-bs-toggle="dropdown"
          id="dropdownMenuButton1"
          aria-expanded="false"
        >
          Dropdown 
        </button>
        <ul className="dropdown-menu" aria-labelledby="dropdownMenuButton1">
          <li>
            <a className="dropdown-item" href="#">
              Option 1
            </a>
          </li>
          <li>
            <a className="dropdown-item" href="#">
              Option 2
            </a>
          </li>
          <li>
            <a className="dropdown-item" href="#">
              Option 3
            </a>
          </li>
        </ul>
      </div>
    </div>
  );
}

the result :

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-09-15%20a%CC%80%2021.26.34.png?alt=media&token=61bd5ba0-af55-4f3d-81a2-9c6fe0eeec2c

reactstrap and react-bootstrap

If you want to use ready-to-use Bootstrap Components redesigned internally as JSX, without the need to use JQuery or Javascript with direct DOM manipulation you can use two libraries :

  • reactstrap

this library uses bootstrap class components :

import React from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';

class ModalExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modal: false
    };

    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState(prevState => ({
      modal: !prevState.modal
    }));
  }

  render() {
    return (
      <div>
        <Button color="danger" onClick={this.toggle}>{this.props.buttonLabel}</Button>
        <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
          <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
          <ModalBody>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          </ModalBody>
          <ModalFooter>
            <Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
            <Button color="secondary" onClick={this.toggle}>Cancel</Button>
          </ModalFooter>
        </Modal>
      </div>
    );
  }
}

export default ModalExample; 

react-bootstrap

this library uses react hooks and functions :

function MyVerticallyCenteredModal(props) {
  return (
    <Modal
      {...props}
      size="lg"
      aria-labelledby="contained-modal-title-vcenter"
      centered
    >
      <Modal.Header closeButton>
        <Modal.Title id="contained-modal-title-vcenter">
          Modal heading
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <h4>Centered Modal</h4>
        <p>
          Cras mattis consectetur purus sit amet fermentum. Cras justo odio,
          dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac
          consectetur ac, vestibulum at eros.
        </p>
      </Modal.Body>
      <Modal.Footer>
        <Button onClick={props.onHide}>Close</Button>
      </Modal.Footer>
    </Modal>
  );
}

function App() {
  const [modalShow, setModalShow] = React.useState(false);

  return (
    <ButtonToolbar>
      <Button variant="primary" onClick={() => setModalShow(true)}>
        Launch vertically centered modal
      </Button>

      <MyVerticallyCenteredModal
        show={modalShow}
        onHide={() => setModalShow(false)}
      />
    </ButtonToolbar>
  );
}

render(<App />);