How to customize the background-color of buttons in React JS using className in react-bootstrap PopOver

I am currently working on a React JS component that includes multiple buttons, each of which triggers a different popover or tooltip message. I am trying to assign unique background colors to each popover title. I have added the styling for these colors in my CSS file and in my JSX code, implemented a function that retrieves the appropriate background color styling for each popover. However, the coloring is not displaying as expected. I've noticed others using .popover-titles in the CSS, but this would cause all popovers to have the same color. What I need is to apply individual colors to each button's popover.

Any assistance on this matter would be greatly appreciated. Thank you.

import styles from 'cssFile'

CSS

:local .greenColor
  background-color: F990099
  color: #000000


JSX code

<Popover id="1" title="test title" className={this.getBackgroundColor()}>test</Popover>

// There are multiple Popover elements like this one. I want to use the getBackgroundColor function to retrieve specific styling for each.


getBackgroundColor = () => {
  return 'styles.greenColor';
}

Answer №1

If you want to achieve this effect:

import React from "react";
import ReactDOM from "react-dom";
import Popover from "react-popover";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { id: -1, color: "white", isOpen: false };
  }

  togglePopover = (e, _id, _color) => {
    if (_id !== this.state.id && this.state.isOpen) {
      this.setState({ isOpen: !this.state.isOpen }, function() {
        this.setState({ id: _id, color: _color, isOpen: !this.state.isOpen });
      });
    } else
      this.setState({ id: _id, color: _color, isOpen: !this.state.isOpen });
  };

  render() {
    return (
      <div className="App" style={{ margin: "50px" }}>
        <div>
          <Popover
            style={{ backgroundColor: this.state.color, color: "white" }}
            isOpen={this.state.isOpen && this.state.id === 1}
            body={<div className="Balloon">Popover Content</div>}
          >
            <button onClick={e => this.togglePopover(e, 1, "red")}>
              Toggle Popover
            </button>
          </Popover>
        </div>
        <br />
        <br />
        <div>
          <Popover
            style={{ backgroundColor: this.state.color }}
            isOpen={this.state.isOpen && this.state.id === 2}
            body={<div className="Balloon">Popover Content</div>}
          >
            <button onClick={e => this.togglePopover(e, 2, "yellow")}>
              Toggle Popover
            </button>
          </Popover>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You can also utilize the togglePopover function as a mouse-over method which will work for any number of Popovers without needing to change the internal code.

Check out the answer output: HERE

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

Place the p elements outside of the divs and align them accordingly

I have a div containing multiple p elements and I need to align buttons next to certain p elements. I want the buttons to be displayed only for specific p elements, which will be controlled using JavaScript. Normally, I would put each p element in a separa ...

Using Accordions in Jquery to dynamically adjust page height during ajax calls

I am currently using AJAX to call in a page and animate its height successfully. However, I have encountered an issue with an accordion-like function that is supposed to toggle the visibility of an element and adjust the height of the containing element ac ...

What is the purpose of exporting the metadata variable in the Layout.js file in Next.js?

I've recently started using next.js and I'm a bit confused about why the metadata variable is exported from the Layout file without being imported anywhere. import "./globals.css"; export const metadata = { title: "NextJS App&qu ...

Exploring the new features of utilizing buttons with the onClick method in the updated nextJS version 14.1.3

"implement customer" import React, { useState } from "react"; import { FaChevronLeft, FaChevronRight } from "react-icons/fa"; export default function HeroSlider() { const images = [ "/images/homepage/home-1.jpeg&qu ...

Implementing Rate Limits in Next.js 14: A Guide on Programmatically Invoking React Server Actions

My application has a signup feature that requires users to input their email address, which is then added to the database using FormData. I am interested in simulating rate limiting using only the fetch API. Is there a way to achieve this without relying ...

What is the best way to place a div inside a navbar element inline?

Having a bit of trouble with my HTML code. I'm working on creating an offcanvas navbar. Here's the code snippet: <nav class="navbar navbar-dark bg-dark"> <div class="container-fluid"> <a cl ...

Tips for effectively passing arguments to useCallback

Can you explain how the newValue argument is being passed to the useCallback function in this code snippet from the Shopify Polaris library (ReactJS)? function TextFieldExample() { const [value, setValue] = useState('Jaded Pixel'); const han ...

Create animations for ng-repeat elements without using ng-animate

Can the transition for changing the order of the model array in ng-repeat be animated using only CSS, without using ng-animate? ...

After trying to use react-native init on macOS Catalina, I encountered a frustrating issue where the process would hang indefinitely. The error message displayed was "fetchMetadata: sill resolveWithNewModule

I attempted to create a react native application by using the react-native init command. However, I encountered a hang with the following message: fetchMetadata: sill resolveWithNewModule [email protected] checking installable status It seems many ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

Two sets of scrolling bars

Having an issue with my JSFIDDLE parallax effect causing two scrollbars in the result. How can I ensure there is only one scrollbar for all my content? Here is some of the HTML code: <div id="intro"> <p>Sed uelit, sed quia...</p> </ ...

Unable to perform updates in MongoDB using Mongoose

I'm currently working on implementing a followers/following feature in my project. However, I'm facing difficulties in updating the database correctly. Although I can console.log the IDs successfully, nothing is being updated in the database and ...

I am encountering issues with the responsiveness of my layout as it is

My goal is to create a responsive layout utilizing code and examples from this website: www.responsivegridsystem.com To achieve this, I have nested a few containers to ensure a content area of 960px width centered within a 1000px container. My plan is th ...

React - Customizable Counter Components - Control All Counters with Parent Component

Hello everyone, I'm fairly new to React and still in the learning process. Currently, I have a challenge that involves creating a simple React Counter app with some specific requirements. The challenge is to build the app without using Redux or hooks. ...

What is the best way to prevent one react audio player from continuing to play when starting another?

I'm struggling to implement state tracking to determine which song is currently playing. I'm unsure about the parameters to pass into the React Audio Player and where to set the state. Can anyone help with this? This is the code for the entire co ...

Modify the background hue of a personalized WordPress HTML block using supplementary CSS styling

My current challenge involves modifying the background color of a specific custom HTML WordPress block. However, when I make changes to one block, it affects the background color of all other custom HTML blocks on different pages. Here is the CSS code I a ...

Can you explain the significance of the "--" within CSS selectors?

My CSS skills are not the greatest and I stumbled upon a snippet of code that is puzzling to me. .grid-product__title.grid-product__title--body:hover { text-decoration: underline; } I checked MDN and it usually defines a reusable property, like a vari ...

Is it possible to utilize setState in Redux?

While exploring React, I couldn't help but notice that components maintain internal state through setState. However, my understanding is that Redux operates on a global state. So, does one use setState to interact with Redux as well? ...

Unexpected rendering of data retrieved by React

I'm currently facing a challenge with the display of data using ReactJS. Although I can successfully retrieve data from the API and iterate through each object to display individual "products", I'm encountering a problem where each of the thirte ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...