Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS background-clip property not being applied in React when background is dinamically changing

If you want to jump into live code i prepared this CodeSandBox here: https://codesandbox.io/s/0j99m3m50

Here's what I am doing:

I have React component with state object having two properties (users, gradient) with values

this.state = {
    users: "programmer",
    gradient: "linear-gradient(120deg, #f093fb 0%, #f5576c 100%)"
};

And I am rendering user on an h1 JSX tag, but I should see the text clipped to each random gradient background, however it is not working, why?

render() {
  const gradually = this.state.gradient;
  const userGradient = {
    background: `${gradually}`,
    WebkitBackgroundClip: "text !important",
    backgroundClip: "text !important",
    color: "transparent"
  };

  return (
    <div>
      <h1 style={userGradient} className="text">
        {this.state.users}
      </h1>
    </div>
  );
}
like image 230
waldothedeveloper Avatar asked Sep 18 '25 21:09

waldothedeveloper


1 Answers

You need to add a unique key on your h1 tag to force a repaint. The key could be the same value as your gradually var. You can also get rid of the !important on your clips.

Here's a link to working changes to your sandbox: https://codesandbox.io/s/css-background-clip-not-being-applied-n34o0

const gradually = this.state.gradient;
const userGradient = {
  background: `${gradually}`,
  WebkitBackgroundClip: "text", // Removed !important
  backgroundClip: "text", // Removed !important
  color: "transparent"
};

return (
  <div>
    <h1
      style={userGradient}
      className="text"
      key={gradually} // Add key
      >
      {this.state.users}
    </h1>
  </div>
);
like image 115
Shalanah Avatar answered Sep 21 '25 15:09

Shalanah