Styles and CSS in React


  In React, there are several ways to apply styles to your components. Let's explore some of the most common options for working with styles in React.


Inline Styles

  The most basic approach to applying styles in React is the use of inline styles. Styles are defined as a JavaScript object, where CSS properties are written in camelCase and values are strings.


const Button = () => {
  const buttonStyle = {
    backgroundColor: 'blue',
    color: 'white',
    padding: '10px 20px',
    borderRadius: '5px'
  };

  return <button style={buttonStyle}>Click me</button>;
};

CSS in External Files

  Another common way to apply styles is through external CSS files. In React, you can import a CSS file and use the classes defined in it.


// In Button.css
.button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
}

// In Button.js
import './Button.css';

const Button = () => {
  return <button className="button">Click me</button>;
};

CSS Modules

  CSS Modules allow for a more modular way of working with CSS, where CSS classes are local to the component, avoiding naming collisions between different components.


// In Button.module.css
.button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
}

// In Button.js
import styles from './Button.module.css';

const Button = () => {
  return <button className={styles.button}>Click me</button>;
};

Styled-components

  Styled-components is a library that allows you to write CSS within components, creating dynamic and scoped style components. With this library, you can define styles directly in JavaScript.


import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
`;

const App = () => {
  return <Button>Click me</Button>;
};

Combining Styles

  It is possible to combine several of these techniques in the same component. For example, we can use inline styles along with classes from an external CSS file.


import './Button.css';

const Button = () => {
  const buttonStyle = {
    color: 'red',
  };

  return <button style={buttonStyle} className="button">Click me</button>;
};


What is a CSS style and what is it used for? Is CSS used with React? How many CSS styles are there? Which CSS is best with React? Import CSS in React Style in React React CSS Dynamic styles React CSS in JSX React css styling format React style components React add style to a component