Home > database >  How to use css gradient using a variable in Reactjs?
How to use css gradient using a variable in Reactjs?

Time:11-07

I want to use the following css property in the Navlink component. In CSS file , the property can be written as given below which uses gradient.

.ele {
       background-image:
       linear-gradient(45deg, #808080 25%, transparent 25%), 
       linear-gradient(-45deg, #808080 25%, transparent 25%),
       linear-gradient(45deg, transparent 75%, #808080 75%),
       linear-gradient(-45deg, transparent 75%, #808080 75%);

       background-size:20px 20px;    
       background-position:0 0, 10px 0, 10px -10px, 0px 10px;
}

While using in react taking them as a variable tabStyle as shown below, I know that:

  • background-size changes to backgroundSize
  • background-image changes to backgroundImage
  • background-position changes to backgroundPosition

but how can we use linear-gradient?

NavbarJs Code:

import React from "react";
import { NavLink, useLocation } from "react-router-dom";

const NavbarComponent = () => {

let location = useLocation();

let tabStyle = {
   backgroundImage:
   linearGradient('45deg', '#808080 25%', 'transparent 25%'), 
   linearGradient('-45deg', '#808080 25%', 'transparent 25%'),
   linearGradient('45deg', 'transparent 75%', '#808080 75%'),
   linearGradient('-45deg', 'transparent 75%', '#808080 75%');

  }

return (
  <>
    <nav variant="pills" className="navbar" style={{ borderBottom: "1px solid white" }}>
      <ul className="nav nav-pills">
        <li>
          <NavLink style={location.pathname === "/" ? tabStyle:{}} to="/">Home</NavLink>
        </li>
        <li>
          <NavLink style={location.pathname === "/about" ? tabStyle:{}} to="/about">About</NavLink>
      </li>
      <li>
        <NavLink style={location.pathname === "/articles-list" ? tabStyle:{}} to="/articles-list">Articles</NavLink>
      </li>
    </ul>
  </nav>
</>
 );
};

export default NavbarComponent;

CodePudding user response:

no you don't need to use Camelcase syntax for css functions like linear-gradient just use a simple string

let tabStyle = {
   backgroundImage:
   "linear-gradient(45deg, #808080 25%, transparent 25%)",
   "linear-gradient(-45deg, #808080 25%, transparent 25%)",
   "linear-gradient(45deg, transparent 75%, #808080 75%)",
   "linear-gradient(-45deg, transparent 75%, #808080 75%)";
}

CodePudding user response:

It should be just "linear-gradient()" as a string value of backgroundImage:

  • Related