Bootstrap 5 Tutorial

v5.3.0

Bootstrap 5 Tutorial

Bootstrap 5 with JavaScript Frameworks

Framework Integration: Learn how to use Bootstrap 5 with popular JavaScript frameworks like React, Vue.js, Angular, and Svelte.

Why Integrate Bootstrap with Frameworks?

Modern JavaScript frameworks handle UI differently than traditional websites. Integrating Bootstrap with these frameworks requires special considerations for component lifecycle, state management, and performance.

Component Reusability

Create reusable Bootstrap components within your framework

Performance

Optimized rendering and bundle splitting

Ecosystem Integration

Seamless integration with framework tools and plugins

Integration Approaches

Three Integration Strategies
1. Direct Integration

Include Bootstrap CSS/JS directly and use framework lifecycle methods to initialize components.

  • Pros: Full control, no dependencies
  • Cons: Manual initialization needed
  • Best for: Simple projects, prototyping
2. Wrapper Libraries

Use framework-specific Bootstrap libraries (React Bootstrap, BootstrapVue, etc.)

  • Pros: Native framework components, better integration
  • Cons: Additional dependency, learning curve
  • Best for: Production applications
3. Component Libraries

Use comprehensive UI libraries built on Bootstrap (CoreUI, Material-UI Bootstrap)

  • Pros: Extended components, themes, tools
  • Cons: Vendor lock-in, larger bundle
  • Best for: Enterprise applications
Recommendation:

For most projects, use wrapper libraries (React Bootstrap, BootstrapVue) as they provide the best balance of native framework integration and Bootstrap functionality.

React Integration

Bootstrap with React
Method 1: React Bootstrap (Recommended)

The most popular Bootstrap wrapper for React with native React components.

# Installation
    npm install react-bootstrap bootstrap

    # Or with yarn
    yarn add react-bootstrap bootstrap

    // App.js
    import 'bootstrap/dist/css/bootstrap.min.css';
    import { Container, Button, Modal } from 'react-bootstrap';

    function App() {
    const [show, setShow] = useState(false);
    
    return (
        <Container>
        <Button 
            variant="primary" 
            onClick={() => setShow(true)}
        >
            Open Modal
        </Button>
        
        <Modal show={show} onHide={() => setShow(false)}>
            <Modal.Header closeButton>
            <Modal.Title>React Bootstrap Modal</Modal.Title>
            </Modal.Header>
            <Modal.Body>
            This is a Bootstrap modal in React!
            </Modal.Body>
        </Modal>
        </Container>
    );
    }
Method 2: Direct Integration

Include Bootstrap directly and manage components with React lifecycle.

// index.html
    <link href="bootstrap.min.css" rel="stylesheet">
    <script src="bootstrap.bundle.min.js"></script>

    // ModalComponent.jsx
    import { useEffect, useRef } from 'react';

    function ModalComponent() {
    const modalRef = useRef(null);
    let modalInstance = null;
    
    useEffect(() => {
        // Initialize Bootstrap modal
        if (modalRef.current) {
        modalInstance = new bootstrap.Modal(modalRef.current);
        }
        
        // Cleanup on unmount
        return () => {
        if (modalInstance) {
            modalInstance.dispose();
        }
        };
    }, []);
    
    const showModal = () => {
        if (modalInstance) modalInstance.show();
    };
    
    return (
        <>
        <button onClick={showModal} className="btn btn-primary">
            Show Modal
        </button>
        
        <div className="modal fade" ref={modalRef} tabIndex="-1">
            <div className="modal-dialog">
            <div className="modal-content">
                {/* Modal content */}
            </div>
            </div>
        </div>
        </>
    );
    }
React Bootstrap Features:
  • Native React components
  • TypeScript support
  • Hooks-based API
  • Custom themes support
  • Active maintenance
Common React Issues:
  • Virtual DOM conflicts with jQuery
  • Component lifecycle management
  • Event handling conflicts
  • Server-side rendering (SSR)
  • Bundle size optimization
Popular React Bootstrap Libraries:
LibraryStarsBootstrapFeatures
React Bootstrap21k+v5Official, most popular, hooks support
Reactstrap10k+v4/v5Comprehensive, well-documented
CoreUI React1k+v5Admin templates, premium components
Material-UI86k+InspiredMaterial Design, not pure Bootstrap

Vue.js Integration

Bootstrap with Vue.js
Method 1: BootstrapVue (v2 for Bootstrap 5)

The most comprehensive Bootstrap integration for Vue.js.

# Installation for Bootstrap 5
    npm install bootstrap bootstrap-vue-3

    # For Vue 3
    import { createApp } from 'vue';
    import BootstrapVue3 from 'bootstrap-vue-3';
    import 'bootstrap/dist/css/bootstrap.css';
    import 'bootstrap-vue-3/dist/bootstrap-vue-3.css';

    const app = createApp(App);
    app.use(BootstrapVue3);
    app.mount('#app');

    <!-- Component.vue -->
    <template>
    <BButton variant="primary" @click="showModal = true">
        Open Modal
    </BButton>
    
    <BModal v-model="showModal" title="BootstrapVue Modal">
        <p>This is a Bootstrap modal in Vue.js!</p>
    </BModal>
    </template>

    <script>
    import { BButton, BModal } from 'bootstrap-vue-3';

    export default {
    components: {
        BButton,
        BModal
    },
    data() {
        return {
        showModal: false
        };
    }
    };
    </script>
Method 2: Direct Vue 3 Integration

Use Bootstrap directly with Vue 3 Composition API.

<!-- ModalComponent.vue -->
    <template>
    <button @click="showModal" class="btn btn-primary">
        Show Modal
    </button>
    
    <div class="modal fade" ref="modalEl" tabindex="-1">
        <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
            <h5 class="modal-title">Vue Modal</h5>
            <button 
                type="button" 
                class="btn-close" 
                @click="hideModal"
            ></button>
            </div>
            <div class="modal-body">
            Modal content
            </div>
        </div>
        </div>
    </div>
    </template>

    <script setup>
    import { ref, onMounted, onUnmounted } from 'vue';
    import { Modal } from 'bootstrap';

    const modalEl = ref(null);
    let modalInstance = null;

    onMounted(() => {
    if (modalEl.value) {
        modalInstance = new Modal(modalEl.value);
    }
    });

    onUnmounted(() => {
    if (modalInstance) {
        modalInstance.dispose();
    }
    });

    const showModal = () => {
    if (modalInstance) modalInstance.show();
    };

    const hideModal = () => {
    if (modalInstance) modalInstance.hide();
    };
    </script>
BootstrapVue Features:
  • Vue 3 compatible (bootstrap-vue-3)
  • Comprehensive component library
  • Directive support
  • TypeScript definitions
  • Icon components
Vue Integration Notes:
  • BootstrapVue v2 supports Bootstrap 5
  • Use bootstrap-vue-3 for Vue 3
  • Directives for tooltips/popovers
  • Form integration with v-model
  • Server-side rendering support

Angular Integration

Bootstrap with Angular
Method 1: ng-bootstrap (Recommended)

Native Angular directives for Bootstrap components.

# Installation
    ng add @ng-bootstrap/ng-bootstrap

    # Or manually
    npm install @ng-bootstrap/ng-bootstrap

    // app.module.ts
    import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

    @NgModule({
    imports: [
        NgbModule,
        // other imports
    ]
    })
    export class AppModule { }

    <!-- modal.component.html -->
    <button class="btn btn-primary" (click)="openModal()">
    Open Modal
    </button>

    <ng-template #modalContent let-modal>
    <div class="modal-header">
        <h5 class="modal-title">Angular Modal</h5>
        <button type="button" class="btn-close" 
                (click)="modal.dismiss()"></button>
    </div>
    <div class="modal-body">
        <p>This is a Bootstrap modal in Angular!</p>
    </div>
    </ng-template>

    // modal.component.ts
    import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

    export class ModalComponent {
    @ViewChild('modalContent') modalContent: any;
    
    constructor(private modalService: NgbModal) {}
    
    openModal() {
        this.modalService.open(this.modalContent);
    }
    }
Method 2: ngx-bootstrap

Alternative Bootstrap library for Angular with different API.

# Installation
    npm install ngx-bootstrap

    // app.module.ts
    import { ModalModule } from 'ngx-bootstrap/modal';
    import { AlertModule } from 'ngx-bootstrap/alert';

    @NgModule({
    imports: [
        ModalModule.forRoot(),
        AlertModule.forRoot()
    ]
    })

    <!-- Using directives -->
    <button type="button" class="btn btn-primary"
            (click)="modal.show()">
    Open Modal
    </button>

    <div bsModal #modal="bs-modal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">ngx-bootstrap Modal</h5>
            <button type="button" class="btn-close"
                    (click)="modal.hide()"></button>
        </div>
        </div>
    </div>
    </div>
ng-bootstrap Features:
  • Native Angular implementation
  • No jQuery dependency
  • TypeScript first
  • AOT compilation support
  • Accessibility compliant
Angular Integration Notes:
  • Choose between ng-bootstrap or ngx-bootstrap
  • Consider Ivy compatibility
  • Watch for bundle size with tree-shaking
  • Use Angular animations or CSS transitions
  • Test with Ahead-of-Time compilation

Svelte Integration

Bootstrap with Svelte
Method 1: sveltestrap

Bootstrap components for Svelte applications.

# Installation
    npm install sveltestrap bootstrap

    // App.svelte
    <script>
    import 'bootstrap/dist/css/bootstrap.min.css';
    import { Button, Modal, ModalHeader, ModalBody } from 'sveltestrap';
    
    let modal = false;
    </script>

    <Button color="primary" on:click={() => modal = true}>
    Open Modal
    </Button>

    <Modal {modal} toggle={() => modal = !modal}>
    <ModalHeader toggle={() => modal = false}>
        Svelte Modal
    </ModalHeader>
    <ModalBody>
        This is a Bootstrap modal in Svelte!
    </ModalBody>
    </Modal>
Method 2: Direct Svelte Integration

Use Bootstrap directly with Svelte's reactive statements.

<!-- Modal.svelte -->
    <script>
    import { onMount, onDestroy } from 'svelte';
    import { Modal } from 'bootstrap';
    
    export let title = 'Modal Title';
    export let open = false;
    
    let modalElement;
    let modalInstance;
    
    $: if (open && modalInstance) {
        modalInstance.show();
    }
    
    onMount(() => {
        if (modalElement) {
        modalInstance = new Modal(modalElement);
        }
    });
    
    onDestroy(() => {
        if (modalInstance) {
        modalInstance.dispose();
        }
    });
    
    function closeModal() {
        if (modalInstance) {
        modalInstance.hide();
        }
        open = false;
    }
    </script>

    <div class="modal fade" bind:this={modalElement} tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">{title}</h5>
            <button type="button" class="btn-close" 
                    on:click={closeModal}></button>
        </div>
        <slot />
        </div>
    </div>
    </div>
Svelte Integration Advantages:
  • Compile-time optimization: Svelte compiles away framework code
  • Small bundle size: Minimal runtime overhead
  • Reactive statements: Easy integration with Bootstrap state
  • Direct DOM access: Simple Bootstrap component initialization
  • Growing ecosystem: Increasing library support

Framework Comparison

Framework Integration Summary
FrameworkRecommended LibraryBundle Size ImpactLearning CurveBest For
ReactReact BootstrapMedium (40-80KB)LowSPAs, dashboards, web apps
Vue.jsBootstrapVue (v2/v3)Medium (50-90KB)LowProgressive web apps, prototypes
Angularng-bootstrapMedium (60-100KB)MediumEnterprise applications
SveltesveltestrapSmall (20-40KB)LowPerformance-critical apps
Any FrameworkDirect integrationMinimal (Bootstrap only)HighSimple use cases, custom needs

Best Practices for Framework Integration

Framework-Specific Best Practices
Component Lifecycle Management
// React: Use useEffect for initialization
    useEffect(() => {
    // Initialize Bootstrap component
    const modal = new bootstrap.Modal(modalRef.current);
    
    // Cleanup on unmount
    return () => modal.dispose();
    }, []);

    // Vue: Use lifecycle hooks
    onMounted(() => {
    // Initialize
    modalInstance = new bootstrap.Modal(modalEl.value);
    });

    onUnmounted(() => {
    // Cleanup
    if (modalInstance) modalInstance.dispose();
    });

    // Angular: Use ngOnInit and ngOnDestroy
    ngOnInit() {
    this.modalInstance = new bootstrap.Modal(this.modalEl);
    }

    ngOnDestroy() {
    this.modalInstance.dispose();
    }
State Management Integration
// Keep Bootstrap state in sync with framework state

    // React: Use state with useEffect
    const [isModalOpen, setIsModalOpen] = useState(false);

    useEffect(() => {
    if (modalInstance) {
        if (isModalOpen) {
        modalInstance.show();
        } else {
        modalInstance.hide();
        }
    }
    }, [isModalOpen]);

    // Vue: Use watchers
    watch(() => props.open, (newVal) => {
    if (modalInstance) {
        if (newVal) {
        modalInstance.show();
        } else {
        modalInstance.hide();
        }
    }
    });

    // Angular: Use property binding with ngOnChanges
    ngOnChanges(changes: SimpleChanges) {
    if (changes.open && modalInstance) {
        if (this.open) {
        modalInstance.show();
        } else {
        modalInstance.hide();
        }
    }
    }
Performance Optimization Tips:
  • Lazy load components: Only import what you need
  • Use framework's tree-shaking: Let bundler remove unused code
  • Code splitting: Split Bootstrap components by route
  • Server-side rendering: Handle Bootstrap JS initialization carefully
  • Virtual scrolling: For large lists with Bootstrap components
  • Debounce events: Prevent excessive re-renders
  • Memoize components: Use React.memo, Vue computed, etc.
  • Optimize bundle: Import individual Bootstrap components
  • Use CDN in development: Faster iteration, smaller bundles
  • Monitor performance: Use framework dev tools

Common Issues & Solutions

Framework Integration Issues
IssueFrameworkSolution
Components not initializingAllInitialize in appropriate lifecycle hook (useEffect, mounted, ngOnInit)
Memory leaksReact, Vue, AngularAlways dispose Bootstrap instances in cleanup/unmount hooks
State out of syncReact, VueUse watchers/useEffect to sync Bootstrap state with framework state
SSR hydration errorsNext.js, Nuxt.jsUse dynamic imports or check for window object before initializing
Bundle size too largeAllImport individual components, use tree-shaking, code splitting
Event conflictsReact, VueUse event.stopPropagation() or framework-specific event modifiers
TypeScript errorsReact, Angular, Vue 3Install proper type definitions or use typed wrapper libraries

Migration Strategies

Migrating from Bootstrap 4
  • Update wrapper library: React Bootstrap v2, BootstrapVue v2
  • Remove jQuery: Most wrapper libraries drop jQuery in v5 versions
  • Update class names: ml-* to ms-*, mr-* to me-* for RTL support
  • Check form changes: Form components may have updated APIs
  • Test custom components: Custom integrations may need updates
Migrating Between Frameworks
  • Plan component by component: Don't rewrite everything at once
  • Create abstraction layer: Isolate Bootstrap-specific code
  • Use TypeScript: Easier to catch type errors during migration
  • Update tests: Framework changes often require test updates
  • Consider hybrid approach: Run both frameworks during transition
Migration Checklist:
  • ✅ Update wrapper library to Bootstrap 5 compatible version
  • ✅ Remove jQuery dependencies if present
  • ✅ Update spacing utilities (ml-* → ms-*, mr-* → me-*)
  • ✅ Test form components and validation
  • ✅ Verify JavaScript components work with new initialization
  • ✅ Check custom CSS overrides for breaking changes
  • ✅ Update build process and dependencies
  • ✅ Test on all target browsers and devices
Framework Integration Summary
  • Choose the right approach: Wrapper libraries for production, direct integration for simple cases
  • Manage component lifecycle: Initialize in mount hooks, clean up in unmount hooks
  • Keep state synchronized: Use framework reactivity to manage Bootstrap component state
  • Optimize performance: Leverage tree-shaking, code splitting, and lazy loading
  • Test thoroughly: Framework interactions can introduce subtle bugs
  • Stay updated: Bootstrap and framework ecosystems evolve quickly
  • Consider accessibility: Ensure integrated components maintain accessibility features
  • Document integration patterns: Team knowledge sharing is crucial for maintenance
Quick Checklist