CSS Selectors and React

Believe it or not CSS selectors are a not-to-go for styling in React. I usually prefers TailwindCSS or styled-components for most of my projects, but sometimes you don't need extra package in your project.

CSS Selectors

The Issue with inline styles

There's no way you can use inline styles in React as you use them traditionaly. You have to use a CSS class. I found a article by FreeCodeCamp about styles in react.

Well it gathered my attention about using CSS selectors with inline css. So I decided to write a small article about it. I hope you will find it useful.

Are there advantages?

  • No need for extra package.
  • And they are quick.
  • No need to use class.

Today I'm going to show you how to mutate css selectors with useState and pointer events.:

function Text() {
return (
  <div
    style={{
      color: 'red,
    }}>
    Click Me
  </div>
  )
}

Let's move the styles to another object.

const TextStyle = {
  color: 'red,
};

export function Text() {
 return (
  <div
    style={TextStyle}>
    Sample Text
  </div>
  )
}

Now we are going to use useState hook to change the color of the Text on hover.

import { useState } from 'react'

const TextStyle = ({ hover }) => ({
  color: hover ? 'yellow' : 'red',
})

export default function Text() {
  const [hover, setHover] = useState(false)
  return (
    <div
      style={TextStyle({ hover })}
      onPointerOver={() => setHover(true)}
      onPointerOut={() => setHover(false)}
    >
      Click Me
    </div>
  )
}

The useState and pointer events helped us to transform the color of Text. I rarely used inline styles in React before, but I think it's a good example.

Also this is my first post. I hope you will like it. Let me know! I'm always open to feedback.