React style css variables

Handling CSS variables (Custom Properties) in React

In this article, I’ll explain how to handle (update) CSS variables in React. I’ll give you the concept for both Class components approach and Hooks approach.

CSS Custom Properties or variables are a great way to update styles in your app without using pre or post processors or creating additional CSS classes.

A quick reminder on the browser support for the CSS Variables:

Can I Use CSS Variables (Custom Proprties)? Data on support for the CSS Variables (Custom Properties) feature across the major browsers from caniuse.com.

In this example, I’ll be using a simple button component with an onCLick event which will change background-color and color properties of the button, just for the sake of demonstration.

Markup

For the markup, we’ll be using a button element inside a div container. The .container will store the CSS variables for the button.

 class="container">  className="btn">Click me!  

NOTE: The reason we’ve wrapped button inside a container is that there might be other elements and storing CSS variables on the container will scope them only for the child elements of this container.

Style

Let’s define the initial CSS variables on the .container element and use them on the button .

.container  --btn-bg-color: #ff9900; --btn-color: #1780cc; > .btn  background-color: var(--btn-bg-color); color: var(--btn-color); padding: 15px 30px; border: none; cursor: pointer; > 

Now for the React part. Conceptually Class and Hooks approaches are very similar, we’ll go through each one of them step by step.

1. React Class component approach

Let’s create a React class and name it ButtonClassComponent .

class ButtonClassComponent extends React.Component  > 

Then we’ll define the default state in the constructor method. The state will hold only one property isClicked .

constructor (props)  super(props) this.state =  isClicked: false > > 

Next, we’ll create a render method. As you can see, now it just returns the markup like above.

render ()  let btnText = 'Click me!' return ( div className='container'> button className='btn'> btnText> button> div> ) > 

Then let’s create a cssProperties object inside render method and assign this object to a style attribute. This way CSS variables and other CSS properties will be assigned to a .container element if exists.

render ()  let cssProperties = <> let btnText = 'Click me!' return ( div className='container' style=cssProperties>> button className='btn'> btnText> button> div> ) > 

Finally let’s add an onClick event to a button element. The handler will be a this.setState method call. And also let’s add a condition where we check if the button was clicked. If so, we’ll assign properties to a cssProperties object and change button text.

render ()  let cssProperties = <> let btnText = 'Click me!' if (this.state.isClicked)  btnText = 'Hello World!' cssProperties['--btn-bg-color'] = '#1780cc' cssProperties['--btn-color'] = '#ff9900' > return ( div className='container' style=cssProperties>> button className='btn' onClick=() =>  this.setState( isClicked: !this.state.isClicked >) >>> btnText> button> div> ) > 

Final React class component should look like this:

class ButtonClassComponent extends React.Component  constructor (props)  super(props) this.state =  isClicked: false > > render ()  let cssProperties = <> let btnText = 'Click me!' if (this.state.isClicked)  btnText = 'Hello World!' cssProperties['--btn-bg-color'] = '#1780cc' cssProperties['--btn-color'] = '#ff9900' > return ( div className='container' style=cssProperties>> button className='btn' onClick=() =>  this.setState( isClicked: !this.state.isClicked >) >>> btnText> button> div> ) > > 

2. React Hooks approach

This is very similar to a Class component. For the Hooks approach, let’s create a function, and name it ButtonHooksComponent .

function ButtonHooksComponent ()  > 

This function will return the known markup.

function ButtonHooksComponent ()  let cssProperties = <> let btnText = 'Click me!' return ( div className='container' style=cssProperties>> button className='btn'> btnText> button> div> ) > 

Assuming you’ve already imported useState hook, we’ll add a default state.

function ButtonHooksComponent ()  const [ isClicked, setIsClicked ] = useState(false) let cssProperties = <> let btnText = 'Click me!' return ( div className='container' style=cssProperties>> button className='btn'> btnText> button> div> ) > 

Finally let’s add an onClick event and a condition like in the class component.

function ButtonHooksComponent ()  const [ isClicked, setIsClicked ] = useState(false) let cssProperties = <> let btnText = 'Click me!' if (isClicked)  btnText = 'Hello World!' cssProperties['--btn-bg-color'] = '#1780cc' cssProperties['--btn-color'] = '#ff9900' > return ( div className='container' style=cssProperties>> button className='btn' onClick=() => setIsClicked(!isClicked)>>> btnText> button> div> ) > 

So the main concept is to set the desired CSS properties to an object conditionally and then assign this object to a style attribute of an element.

You can use that approach not only for style attribute but also to set other HTML attributes as well. That way your code will be more readable and clear.

You can check the end result and whole code on CodePen:

See the Pen gOYdayy by Nikita Hlopov (@nikitahl) on CodePen.

Источник

Using CSS Variables to Tame Styled Component Props

When I started writing React components about 3 years ago our code base was full of SCSS. This quickly became unmanageable, not because of SCSS, but as a result of all the styles being overwritten in new components as I was converting an Angular library. At the time, afaik(new), there were only 2 ways to keep your styles isolated and scoped in React: Style objects in JS and CSS Modules. The ecosystem has evolved a lot in 3 years. Today we have a lot of options for scoped styles in React. I have leaned towards styled-components for a majority of projects to date. There are a lot of things I love about this library. From the SCSS inspired syntax to the ability to create and inherit styles, this library is a solid solution for scoping styles to components and implementing it «feels» good to me. One of my favorite features of styled-components is the ability to pass in props and leverage these props to manipulate styles. It is a lot like using the classnames package without having to declare individual classes for every prop-related style update. The following is an example of a button.

Button>Click Me!/Button> const Button = styled.button` background-color: gray; `; 

In this example the default Button color is gray . Traditionally, if we wanted to update the background color for a Primary variant of Button we would need to add a className to the Button in order to manipulate the style or pass the background-color override in as a style update on the Button in our jsx.

Button className="primary">Click Me!/Button> const Button = styled.button` background-color: gray; &.primary < background-color: blue; >`; 

As you can see, styled-components provides a way for us to add variant classes without the need for the classnames package, but there is a better way to handle this built into the styled API. We can manipulate variants based on props that are passed to our Button ! Take a look at the following:

Button variant="primary">Click Me!/Button> const Button = styled.button` background-color: props.variant === "primary" ? "blue": "gray">; `; 

Now, with a little ternary action, we can actually toggle the color of our button based on the value passed into the variant prop. Cool, right? This is one of the features that makes styled-components feel so React-like. Normally, this approach is fine, but when we start adding more props-based styles into the mix, our Button can get busy and the variants can be hard to grok when we come back to it for future iterations. Like such:

Button variant="primary" shape="rounded" weight="bold" size="large" >Click Me!/Button> const Button = styled.button` background-color: props.variant === "primary" ? "blue": "gray">; color: props.variant === "primary" ? "white": "charcoal">; border-radius: props.shape === "rounded" ? "8px": "0">; font-weight: props.weight === "bold" ? "700": "400">; font-size: props.size === "large" ? "18px": "12px">; padding: props.size === "large" ? "1rem": "0.5rem">; `; 

As you can see, all the variations on our button quickly get lost in the stack of ternary operations inside of our styles block. Not only this, but without adding in a type-checking library it is hard to follow which props we are actually expecting in our styled.button . If we wanted to update only the font-weight of a bold button, we would have to sift through this mess of ternaries. If we wanted to add a 3rd option for font-weight it would get even messier. Enter CSS Variables. Fortunately, CSS variables are supported by styled components and can easily be inserted into our styles block to ensure our intentions are clear to the next developer that inherits our button code (or our future selves). Take a look at the styled.button when we apply CSS Variables to every prop option.

Button variant="primary" shape="rounded" weight="bold" size="large" >Click Me!/Button> const Button = styled.button` --props-variant-default-background-color: gray; --props-variant-default-color: charcoal; --props-variant-primary-background-color: blue; --props-variant-primary-color: white; --props-variant-primary: blue; --props-shape-default: 0; --props-shape-rounded: 8px; --props-weight-default: 400; --props-weight-bold: 700; --props-size-default-size: 12px; --props-size-large-size: 18px; --props-size-default-padding: 0.5rem; --props-size-large-padding: 1rem; background-color: props.variant === "primary" ? "var(--props-variant-primary-background-color)" : "var(--props-variant-default-background-color)">; color: props.variant === "primary" ? "var(--props-variant-primary-color)" : "var(--props-variant-default-color)">; border-radius: props.shape === "rounded" ? "var(--props-shape-rounded)" : "var(--props-shape-default)">; font-weight: props.weight === "bold" ? "var(--props-weight-bold)" : "var(--props-weight-default)">; font-size: props.size === "large" ? "var(--props-size-large-size)" : "var(--props-size-default-size)">; padding: props.size === "large" ? "var(--props-size-large-padding)" : "var(--props-size-default-padding)">; `; 

Alright, I know, this approach is more verbose for sure. It will take you more lines of code than the original implementation. However, your future self will thank you, because there is no need for guessing or fishing through ternaries or switch statements. It is very obvious where I go to update the font size of a large variant to 20px . It is also clear what props we are expecting. We can also use CSS Variables to toggle properties inside of media queries:

const Button = styled.button` --props-size-default: 12px; --props-size-large: 18px; @media screen and (min-width: 860px) < --props-size-default: 14px; --props-size-large: 20px; >font-size: props.size === "large" ? "var(--props-size-large)" : "var(--props-size-default)">; `; 

That is all! Have fun adding CSS Variables to your Styled Components! Let me know any other ways you have incorporated CSS Variables into your React workflow.

Источник

CSS Variables with HTML and CSS

Alt Text

In a typical app which consists of HTML ,CSS and JS the CSS file is linked to the html file and we have the root pseudo selector as shown below.
Now in a react app its a SPA but its component based structure. Each component has a separate CSS file attached to it. So the question is how can we have a common set of CSS variables which can be used throughout the application?

CSS Variables in React applications

This is a standard react application structure.
Alt Text
We have the index.css file where we can define the root pseudo selector. In that we can define the CSS variables which we can use throughout the application.
Alt Text
Now we need to import the index.css file into the index.js file as shown below.
Alt Text Now we can use these declared CSS variables throughout the app. Because React being a SPA all the variables declared in index.css will be applicable throughout the application as shown in the app.css file image below.
Alt Text Thank you for reading this article

Источник

Читайте также:  Base64 icon in html
Оцените статью