CSS - Update BackgroundColor Depending on Child Element Color

Is there an official CSS way to change the background color based on the child element in HEX?

For example:

render() {
    return (
        ...
    <span>
        <h3 style={{ color: item.color }}>Item Color</h3>
    </span>
      ...
 }

I have experimented with mixBlendMode (mix-blend-mode) but it does the opposite of what I am trying to achieve.

If the text color of the h3 element is white and the background color of the span element is also white, I want to change it to black. Similarly, if the text color is black, then the background should be white.

Is there a standardized way in CSS to accomplish this? Alternatively, is there a method using JavaScript to detect the color from a HEX value?

If the text color is white, then the background color should be black.

If the text color is black, then the background color should be white.

(And likewise for other colors)

Answer №1

If you're looking for a simpler method, I have a solution that might work for you. Here's what I came up with:

Start by adding a reference tag to the element you want to monitor:

<h3 ref={"tag"} style={{ color: item.color }}>Item Color</h3

Then, utilize lifecycle methods to track the color and store it in React state:

componentDidMount() {
    let taggedColor = window.getComputedStyle(this.refs.tag);
    this.setState({
      taggedColor: taggedColor.color
    });
  }

  componentDidUpdate() {
    let taggedColor = window.getComputedStyle(this.refs.tag);
    if (taggedColor.color !== this.state.taggedColor) {
      this.setState({
        taggedColor: taggedColor.color
      });
    }
  }

The getComputedStyle function converts HEX values to RGB, allowing you to use conditional statements based on the RGB colors:

<span
        style={
          this.state.taggedColor === "rgb(17, 17, 17)"
            ? { backgroundColor: "#fff" }
            : { backgroundColor: "#111" }
        }
        className="App"
      >
         <h3 ref={"tag"} style={{ color: item.color }}>Item Color</h3
      </span>

There may be simpler approaches out there, but this is the solution I devised. Feel free to explore other options as well.

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

Ways to display additional text with a "Read More" link after three lines of content without relying on a

I am currently working on an application where I need to display text in a limited space of 3 lines. If the text exceeds this limit, I want to show either "Read More" or "Hide". Below is the code snippet that I am using for this functionality. class Cust ...

What could be the reason the background-color isn't changing when I apply button:hover?

body{ font-family:"Arial","Lucida Grande", "Lucida Sans Unicode", Verdana, Helvetica, sans-serif; font-size:12px; } p, h1, form, button{border:0; margin:0; padding:0;} .spacer{clear:both; height:1px;} /* ----------- My Form ----------- */ .myform{ margin:0 ...

Ways to stop a background image from repeating?

<div style="background-image: url('https://i.ibb.co/v1B855w/bg15.png'); color: #000000; background-color: #000000; background-attachment: fixed; text-align: center;"><img src="https://i.ibb.co/L6zQY0S/name6.png" /> ...

Troubleshooting issues with React styled components and child elements not responding to media queries?

I've been working on a styled component where I'm targeting nested images for individual positioning. I recently tried to add a media query to the main component, but every time I place it above the nested images, it throws a syntax error. Check ...

Steps for adding a forked version of a library in package.json

Recently, I came across a React JS library called React Pacomo. Since the original version of this library is no longer being maintained, I decided to use my own forked version for my project. However, I am facing issues with compiling or building the libr ...

Tips for keeping my wordpress menu at the forefront

This piece of code is responsible for controlling the main menu on my website. Currently, it's set up so that when I scroll down, the menu disappears, and when scrolling up, it reappears. However, I would like the menu to always remain displayed at t ...

Utilizing a flexbox container within a table container, implementing PRE tags for handling overflow

Currently, I am diligently working on an intricate DASHBOARD utilizing bootstrap-4. A peculiar issue arose with the implementation of <pre> within a Flexbox. However, upon closer inspection, it became evident that this was not a flexbox or <pre> ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

The Iframe contains its own scroll feature within the body

I am facing an issue with displaying an Iframe inside a modal. The challenge is that the content within the Iframe varies in height, making it difficult to set a fixed height for the Iframe itself. When I try setting the height to 100%, the result is a 150 ...

React Native SectionList Divided by Dates

I have a task to reformat my date object where I have an array of dates in the following format: Object { "FREETIME": "2021-04-19 11:30:00", }, Object { "FREETIME": "2021-04-19 12:00:00", }, Object ...

What are some best practices for implementing responsive design using CSS @media queries with makeStyles in React.js Material UI?

const useStyles = makeStyles(theme => ({ wrapper: { width: "300px" }, text: { width: "100%" }, button: { width: "100%", marginTop: theme.spacing(1) }, select: { width: "100%", marginTop: theme.spacing(1) } })); I ...

Dynamic Pagination with MUI Counting

I'm currently utilizing mui react for my current project. Within the Pagination component, I am required to input the count in order to display the total number of pages. For example, with a total of 27 products, and each page displaying 20 products ...

Difficulty in monitoring the present machine status through XState in a React application

I'm encountering an issue where I am trying to access the Machine state from within a function in a React component using state.value. However, the current state never changes and it always displays the initial state. Strangely, if I include an onClic ...

What are the pros and cons of embedding background image data into CSS as Base64?

While examining the source code of a greasemonkey userscript, I came across some interesting CSS: .even { background: #fff url(data:image/gif;base64,R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsK ...

What causes a TypeError (Invalid response status code) when a 204 response is returned to a fetch() call within a React Server Component?

Take a look at this straightforward Next.js application: https://codesandbox.io/p/sandbox/next-js-app-router-1bvd7d?file=README.md Here is an API route (/api/hello): export default function handler(req, res) { res.status(204).end(); } And there's ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

Struggling to change h2 style on WordPress?

In a WordPress page, I create three heading texts and adjust the CSS when the screen width is less than 820px. Here is the code snippet: <h1 class="block-h1">Heading 1</h1> <h2 class="block-h2">Heading 2</h2> <h3 class="block-h3 ...

Is there a way to prevent the Material UI Chip component from appearing when there is no content present?

I have developed an application that pulls content from an API and displays it on the screen. Within this app, I have implemented a Material UI Card component to showcase the retrieved information, along with a MUI Chip component nested within the card. &l ...

Error encountered when attempting to integrate FontAwesome into the body of a Next.js Link

I'm currently using the react-fontawesome library in my project built with Next.js. However, I've encountered an issue when trying to include an icon inside the Link component. The error message is confusing and I can't seem to figure out wh ...

Choose the element that is trapped within the div

I've hit a roadblock with this issue that I just can't seem to figure out. I was working on a practice project creating a Netflix-like webpage, and the select element in the footer containing languages is stuck and won't budge. Here's m ...