Nitin Shinde
Nitin Shinde

Reputation: 1244

How to change font color based on background color using reactJs

I have dynamic background of my container it will change by User so I need to set text color based of background color eg, I set black background of my container then i need to set white color for text, I am using ReactJs and material UI library for my App, please suggest some good path.

Upvotes: 4

Views: 4929

Answers (2)

Humberto
Humberto

Reputation: 23

page:

<div className="divao">
   <span className="textao">UAU</span>
</div>

css:

.divao{
   background: #000;
}
.textao{
   color: #FFF;
   mix-blend-mode: exclusion;
}

with this code the color of the .textao class automatically changes.

Upvotes: 2

Beginner
Beginner

Reputation: 9135

see the below sample code.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import DynamicContainer from "./style";

import "./styles.css";

function App() {
  const [bgColor, setBGColor] = useState("#422DAD");
  const [textColor, setTextColor] = useState("rgb(99,99,100)");

  function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
      return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result
      ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16)
        }
      : null;
  }

  useEffect(() => {
    let { r, g, b } = hexToRgb(bgColor);
    let targetColor = `rgb(${r},${g},${b})`;
    var colors = targetColor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    var brightness = 1;

    var R = colors[1];
    var G = colors[2];
    var B = colors[3];

    var ir = Math.floor((255 - R) * brightness);
    var ig = Math.floor((255 - G) * brightness);
    var ib = Math.floor((255 - B) * brightness);
    setTextColor(`rgb(${ir}, ${ig}, ${ib})`);
  }, [bgColor]);

  const handleBgChange = e => {
    setBGColor(e.target.value);
  };

  return (
    <>
      <DynamicContainer bgColor={bgColor} textColor={textColor}>
        Hello World!
      </DynamicContainer>
      <p>Choose Background color</p>
      <input type="color" value={bgColor} onChange={handleBgChange} />
    </>
  );
}

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

here is the upadted codesandbox

check here

Upvotes: 2

Related Questions