Could there be an issue with my website's bootstrap where badges are not being applied properly?

Currently, I am in the process of learning ReactJS and running into an issue where my bootstrap is not working within my .jsx file. Despite following a tutorial (MOSH) diligently and extensively researching on stack overflow, I have not been able to find a solution. I came across someone with a similar problem who resolved it by importing CSS. I attempted to do the same but to no avail. My goal is to display a badge next to a button, however, the button shows up but the badge does not. Additionally, I've tried reinstalling bootstrap multiple times without success.

index.js:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';
    import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
    import Counter from './components/counter';

    ReactDOM.render(<Counter />, document.getElementById('root'));


    reportWebVitals();

counter.jsx:

    import React, { Component } from "react";

    class Counter extends Component {
    state = {
        count: 0,
        
    };  

    render() {
        return (
            <div>
            
                <span className = "badge badge-primary">{this.formatCount()}</span>
                <button>Increment</button>
            </div>
        );
    }

    formatCount(){
      const {count} = this.state;
      return count === 0 ? 'Zero' : count;
    }
}

export default Counter;

Answer №1

It seems that there is an issue with the bootstrap class name used for the badge in your code. This could be due to you having the latest version of bootstrap (v5.1) installed. The badge will work correctly on older versions like v4.6. To fix this problem, try using:

className = "badge bg-primary"
or consider downgrading to the older bootstrap version.

  • For bootstrap v5.1:
    <span className = "badge bg-primary"></span>
  • For bootstrap v4.6 (or below):
    <span className = "badge badge-primary"></span>

Here are links to the documentation for bootstrap v5.1 and v4.6:

After testing your code, I recommend a simpler approach for implementing a counter:

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import Counter from './Counter.jsx';

ReactDOM.render(<Counter />, document.getElementById('root'));

Counter.jsx

import React, { useState } from "react";

function Counter(){
    let [count, setCount] = useState(0);

    return (
        <div className="container">
            <span className = "badge bg-primary">{formatCount()}</span>
            <button className="btn btn-success" onClick ={increase}>Increment</button>
        </div>
    );

    function increase(){
        setCount(count + 1);

    }

    function formatCount(){
        return (count === 0 ? 'Zero' : count);
         }
    
}

export default Counter;

To address styling issues, I've added a custom CSS class for centering components:

styles.css:

 .container {
    text-align: center;
    margin: 20% auto;
}

Solution for style problems

  • Utilize the ternary operator to dynamically apply different bootstrap classes based on the "count" value. This will switch between "badge bg-warning" and "badge bg-primary" depending on whether count is equal to 0 or not.

Counter.jsx

 import React, { useState } from "react";

function Counter(){
    let [count, setCount] = useState(0);

    return (
        <div className="container">
            <span className = {count === 0 ? "badge bg-warning" : "badge bg-primary"}>{formatCount()}</span>
            <button className="btn btn-success" onClick ={increase}>Increment</button>
        </div>
    );

    function increase(){
        setCount(count + 1);

    }

    function formatCount(){
        return (count === 0 ? 'Zero' : count);
         }
    
}

export default Counter;
  • All other codes remain unchanged.

Resources for further reading:

Answer №2

RenegadeShades, simply by adding the pathway for Bootstrap CSS import in your index.js file, you can elevate the styling of your code:

import "bootstrap/dist/css/bootstrap.css";

In the "Counter.jsx" component, consider using this code if you are working with a different version than what Mosh uses:
<span className = "badge bg-primary">{formatCount()}</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate a click on a div element to enable smooth scrolling when using the page down and page up keys

Whenever I directly click on my div, the pageUp and pageDown keys scroll the contents of the div. But when I trigger a click programmatically, the scrolling with pageUp and pageDown stops working. How can I enable scrolling with pageUp and pageDown without ...

Typescript causing undefined React Router match issue

Currently, I am working on a basic eCommerce Proof of Concept using react and TypeScript. Unfortunately, I am facing an issue where I am unable to pass props to a product detail page or access the match containing the params. This is how my Routes pages a ...

Two consecutive instances of the outcome recorded in the ajax table

I am trying to add data to a table, but one of my results is appearing twice. Here is the JSON response I received: groupname […] 0 {…} survey_id 2 group_name DEMO 1 {…} survey_id 1 group_name TEST This is what my AJAX success function ...

Exploring Node and Express Request Query

I'm struggling with a specific endpoint setup in my code. // GET /api/logs/ app.get('/api/logs', function (req, res) { if (req.query.reverse === true) { res.send((mainModule.logs).reverse()); } else { res.send(mainModule.logs) ...

Creating the CSS styles for input fields

Here is an example of a form: <form class="mystyle" ...> <input name="test1" type="text"> <input name="test2" type="text"> ... </form> I want to apply CSS styling to all the input elements in this form: .mystyle input[type="text" ...

Unlocking the Power of jQuery's toggle Method for Dynamic Functionality

For my project, I require numerous jQuery toggles to switch between text and icons. Currently, I am achieving this by using: $("#id1").click(function () { //Code for toggling display, changing icon and text }); $("#id2").click(function () { //Same co ...

Styling Discord with NodeJS

After coding with Python for Discord, I decided to switch to JavaScript for its wider functionality. However, I encountered a formatting issue with a specific line of code while testing out a music bot in JS. The bot was sending an embed message, but I wan ...

The reducer test did not return a value for GET_SUCCESS and instead returned

it(`should properly handle ${GET_POSTAL_SUCCESS}`, () => { const payload = { postalCode: { postalInfo: { postalCode: '5282', }, }, }; expect(reducer(state, { type: GET_POSTAL_S ...

Node.js: Error - Module 'html' not found

Currently, I am utilizing Node.js and attempting to exclusively serve HTML files without any Jade or EJS engines. Below is the code for my entry point (index.js): var express = require('express'); var bodyParser = require('body-parser&apo ...

Is it practical to extract the page type/name from the CSS of the selected tab?

My website has multiple tabs on a single page and I want to integrate Google Analytics code. However, since all the tabs are part of the same page, I need a way to track which tab the user is interacting with. Would using CSS to check for the selected tab ...

Encountering the error message "SyntaxError: Cannot use import statement outside a module" is often linked with the mui-color-input component and Create React App

After integrating the mui-color-input library into my create-react-app project, I encountered a problem with the component test despite the project building successfully. ● Test suite failed to run Jest encountered an unexpected token Jest fai ...

Is there a way to execute "npm run dev" within cPanel while I am currently working on a Laravel project?

Currently, I am working on a Laravel project and require to execute the following command in Cpanel terminal: npm run dev https://i.sstatic.net/bzxNj.png ...

Utilizing an Office App Ajax that includes an authentication header, the application connects to a secure Web API 2 backend with CORS

I am currently in the process of developing a content panel application for Office. As part of this project, I need to authenticate an account against a server. To accomplish this, I have implemented my own AuthorizationFilterAttribute on my web api 2 con ...

Is there a way to ensure a dialog box is positioned in the center of the window?

After adjusting the dimensions of my jQuery UI dialog box with the following code: height: $(window).height(), width: $(window).width(), I noticed that it is no longer centered on the window. Do you have any suggestions on how I can recenter it? ...

Learn how to utilize JavaScript produced by the `webpack output library` in a `nodejs` application

I'm currently utilizing webpack to bundle my JavaScript into a library that serves two purposes: one for browser usage and the other for integration into Node.js applications. Below is a snippet of my webpack configuration: output: { filename: ...

Endless scrolling with redux and react

I'm facing an issue while trying to implement infinite scroll in a React-based application that utilizes Redux for state management. I am attempting to dispatch an action on page scroll but have been unsuccessful so far. Below is my code snippet: // ...

Error message: "Encountered an issue with Firebase Reacthook: Unable to access properties of undefined (specifically, '_repo

Currently, I am working on developing a hook in Next.js to retrieve user roles from my real-time database. However, I keep encountering an error message stating "Cannot read properties of undefined (reading '_repo')". Below is the implementation ...

Is there a way to apply a custom CSS to Bootstrap without altering its appearance?

Check out this code snippet <link rel="stylesheet" href="css/bootstrap.css"> <link rel="stylesheet" href="css/sub-cat.css"> I am having trouble with my CSS. I tried to modify the "Caption" class in Bootstrap by adding some new styles in "sub- ...

How can I update the language of a button text in a React component?

Looking to update the button labels from a different language to English. Here is how it currently appears: ...

Ways to eliminate unnecessary re-rendering of components that remain unchanged?

I am struggling with a component that contains various other components, such as text fields. Whenever an input is made in the text field, all the components are re-rendered. My goal is to prevent this re-rendering and only update the component that has a ...