Unable to modify the color of the alert notification in JavaScript using React

I've been attempting to create an alert component, but I'm facing an issue with adjusting the color of the alert message.

Upon enabling dark mode in the navbar (located at the bottom of the navbar component code), an alert message confirming the dark mode activation should be displayed. I'm utilizing Bootstrap CSS for this project.

Alert component:

import React from "react";

export default function Alert(props) {
 const capital = (word) => {
   const lower = word.toLowerCase();

   return lower.charAt(0).toUpperCase() + lower.slice(1);
 };
 return (
   props.alert && (
     <div
       className={`alert alert-${props.alert.type} alert-dismissible fade show`}
       role="alert"
     >
       <strong>{capital(props.alert.type)}</strong>: {props.alert.msg}
     </div>
   )
 );
}

Navbar component:

import React from "react";
import PropTypes from "prop-types";
export default function Navbar(props) {
  return (
    <>
      <nav
        className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}
      >
        <div className="container-fluid">
          <a className="navbar-brand" href="/">
            Navbar
          </a>
          <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav me-auto mb-2 mb-lg-0">
              <li className="nav-item">
                <a className="nav-link active" aria-current="page" href="/">
                  Home
                </a>
              </li>
              <li className="nav-item">
                <a className="nav-link" href="/">
                  Link
                </a>
              </li>

              <li className="nav-item">
                <a
                  className="nav-link "
                  href="/"
                  tabIndex="-1"
                  aria-current="page"
                >
                  {props.aboutText}
                </a>
              </li>
            </ul>
            <form className="d-flex mx-2">
              <input
                className="form-control me-2"
                type="search"
                placeholder="Search"
                aria-label="Search"
              />
              <button className="btn btn-outline-success" type="submit">
                Search
              </button>
            </form>

            <div
              className={`form-check form-switch text-${
                props.mode === "light" ? "dark" : "light"
              } mx-2`}
            >
              <input
                className="form-check-input "
                onClick={props.togglemode}
                type="checkbox"
                id="flexSwitchCheckDefault"
              />
              <label
                className={`form-check-label `}
                htmlFor="flexSwitchCheckDefault"
              >
                Enable Dark Mode
              </label>
            </div>
          </div>
        </div>
      </nav>
    </>
  );
}

App.js:

import "./App.css";
import Navbar from "./components/Navbar";
import React, { useState } from "react";
import Alert from "./components/Alert";
function App() {
  const [mode, setMode] = useState("light");
  const [alert, setAlert] = useState(null);
  const showAlert = (message, type) => {
    setAlert({
      msg: message,
      type: type,
    });
    setTimeout(() => {
      setAlert(null);
    }, 1500);
  };
  const togglemode = () => {
    if (mode === "light") {
      setMode("dark");
      document.body.style.backgroundColor = "#042743";
      showAlert("Dark mode has been enabled", "Success");
    } else {
      setMode("light");
      document.body.style.backgroundColor = "white";
      showAlert("Light mode has been enabled", "Success");
    }
  };
  return (
    <>
      <Navbar aboutText="About Myself" mode={mode} togglemode={togglemode} />
      <div className="container " my-3="true">
        <Alert alert={alert} />
      </div>
    </>
  );
}

export default App;

Answer №1

Modify the showAlert method's second argument:

Change "Success" to "success". This adjustment should work.

To simplify the process for you, substitute:

showAlert("Dark mode has been enabled", "Success");

with:

showAlert("Dark mode has been enabled", "success");

at both occurrences within the togglemode function.

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

Issue with exchanging columns in Bootstrap version 5.0

Seeking assistance! I am a beginner with bootstrap and struggling to figure out an issue I'm experiencing. In the attached image(s), my goal is to have the coin image positioned above its corresponding text on the left side when the screen size is red ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...

Revolutionary CSS and jQuery for an Exceptional Top Navigation Experience

I would like to create a top navigation similar to the one on Facebook, using CSS and jQuery. Here is an example: Additionally: Notice how the arrow in the popbox always remains beneath the selected navigation item, and all popboxes have the same width. ...

Obtaining variable content from a JavaScript function

Learning JS with documentation has been a challenging journey for me. The concept of variables inside and outside a function still confuses me. I'm interested in creating a module that allows me to reuse code written in different parts of my program ...

What could be causing the defaultSelectedKeys property in the ant design Menu component to not update when changes are made

Hello there, I'm facing an issue with the Menu component from ant-design. It seems that the menu is not detecting the state changes that are happening. Here's what I am trying to do: when a button is clicked, I want to change the defaultSelected ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

Is it possible to load a JS file without using the require function?

Is there a method to load a JavaScript file without using require, but with fs for instance? I am aware that for JSON files I can utilize: const jsonFile = JSON.parse(fs.readFileSync("/jsonfile.json")) Can the same be done for a JavaScript file? I am inq ...

Tips for passing down props or all the properties of an object to create a dynamic component

I am facing an issue with a v-for loop in my project. The loop is supposed to iterate through objects in a list of todos fetched from the backend. These objects are then passed down to a child component, which displays each todo individually. However, I ha ...

Executing a get request in Backbone without using the Option parameter by implementing the beforeSend method

After gathering insights from the responses to this and this queries, I have formulated the code below for a GET request: var setHeader = function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa($rootScope.login.Gebruikersnaam + ":" + $r ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

The value entered is being displayed twice every time the onChange event occurs in ReactJS

I recently implemented useReducer in my React project and encountered a strange issue where the values I type are being printed double and twice, as shown in the screenshot below. https://i.sstatic.net/KCkSy.png I'm unsure why this is happening. Here ...

The HTTP.GET method seems to be malfunctioning

I'm having some trouble loading an image from a HTTP.GET request into my application. The picture just won't seem to display correctly. Any suggestions on what might be causing this issue? Below is the code I am using: HTML: <ion-view view- ...

Using setTimeout with jQuery.Deferred

I decided to experiment with jQuery Deferred and setTimeout by creating a basic list. <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> In my script, I ...

Guide on implementing a looping settimeout function on a sliding page to dynamically load an HTML template within the Framework 7 framework

My current setup involves using Framework7 (framework7.io). The code below functions correctly on the main view page, utilizing a looping settimeout to refresh signups.html every second: <script type=“text/javascript” src=“code.jquery.com/jquery- ...

Utilizing Next.js to dynamically update data within a div element upon

I have a table set up to display data and I want to transfer the row data into a div when the user clicks on a table row: Currently, I can successfully get the data onclick: const handleClick = (rowData) => { console.log(rowData); } However, I am ...

I'm struggling to comprehend the purpose of this function. [From the Codecademy Contact List exercise]

Within the "for var x in friends" loop, the program aims to search each key within the friends object, such as bill and steve. Subsequently, with the condition "friends[x].firstName === name", the check is made if the first name matches the provided inpu ...

The behavior of JS Array.push may catch you off guard

There seems to be an issue with the push function in my code. The problem lies in the last line of code shown below. export enum non_searchFieldsNames { language = 'language', categories = 'categories', subtitle = 'subt ...

Utilizing the no-data-text attribute in v-combobox with Vuetify: Tips and tricks

My application includes a simple combobox, and I am trying to set a default text message to display when there are no entries in the items props. To achieve this goal, I utilized the no-data-text prop by passing a specific variable to it. <v-combobox ...

Sending data from an HTML textarea to a PHP variable without user input

After spending more than two days searching for a solution to this problem, I am now reaching out directly with my question. Although there have been some hints and partial answers, nothing has definitively resolved the issue I am facing, prompting me to m ...