Styling elements

  • React
  • Examples
  • Styling elements

React example • 3 min read

  • JSX
  • Styles

There are a bunch of different ways you can go about styling your components in React. Here we will only present 3 of the most basic ones.

Global CSS file

This is pretty straightforward, we just need to import a CSS file and it is done! We should be careful tho because even if we import this file within a component file, the styles will be applied globally! The advantage of this method is that you write pure CSS code, and the main disadvantage is that the styles apply globally, so you can find issues with the name-collision of your CSS class names.

.myTitle {
  border: 1px solid black;
  color: red;
}
import React from 'react';

import './styles.css';

function MyComponent() {
  return <h1 className="myTitle">Hello world!</h1>;
}

export default MyComponent;

And if you want to style your component conditionally you can do something like this:

.button {
  color: black;
}

.activeButton {
  color: green;
}
import React, { useState } from 'react';

import './styles.css';

function MyButton() {
  const [isActive, setIsActive] = useState(false);

  const handleClick = () => {
    setIsActive((prevIsActive) => !prevIsActive);
  };

  const activeClassName = isActive ? 'activeButton' : 'button';

  return (
    <button className={activeClassName} onClick={handleClick}>
      Click me!
    </button>
  );
}

export default MyButton;

CSS-in-JS

Another way that is widely used to style React elements is CSS-in-JS and, as the name suggests, it is writing CSS inside our JavaScript files. However, there are some differences and limitations. First, you are not really writing CSS, but a camelCase version of it, for instance, the CSS property background-color will be transformed into backgroundColor, and then, depending on the module you pick to achieve this, it can be difficult to work with some CSS features such as media queries and animation keyframes for example.

import React from 'react';

function MyComponent() {
  const titleStyle = {
    border: '1px solid black',
    backgroundColor: 'blue',
    marginBottom: '15px',
  };

  return <h1 style={titleStyle}>Hello world!</h1>;
}

export default MyComponent;

If we want to render a style conditionally, using CSS-in-JS is even easier. See the code sample below with an example where we are changing the color from black to green every time the button switches to the isActive state.

import React, { useState } from 'react';

function MyButton() {
  const [isActive, setIsActive] = useState(false);

  const handleClick = () => {
    setIsActive((prevIsActive) => !prevIsActive);
  };

  const buttonStyle = {
    color: isActive ? 'green' : 'black';
    padding: '15px',
    backgroundColor: 'white',
  }

  return (
    <button style={buttonStyle} onClick={handleClick}>
      Click me!
    </button>
  );
}

export default MyButton;

CSS modules

TODO