Flat Preloader Icon

CSS and Inline Styles

In React, you can style your components using CSS in various ways, including traditional CSS files, CSS modules, and inline styles. Here’s a brief overview of each approach

Traditional CSS Files

You can create a CSS file and import it into your component
styles.css
				
					.button {
  background-color: blue;
  color: white;
  padding: 10px;
  border: none;
  border-radius: 5px;
}

				
			
Component.js
				
					import React from 'react';
import './styles.css';

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

export default Button;

				
			

CSS Modules

CSS Modules are a way to locally scope CSS by automatically creating a unique class name. This prevents styles from conflicting.
Button.module.css
				
					.button {
  background-color: blue;
  color: white;
  padding: 10px;
  border: none;
  border-radius: 5px;
}

				
			
Button.js
				
					import React from 'react';
import styles from './Button.module.css';

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

export default Button;

				
			

Inline Styles

Inline styles are defined directly in the component using JavaScript objects. They are useful for dynamic styling
				
					import React from 'react';

const buttonStyle = {
  backgroundColor: 'blue',
  color: 'white',
  padding: '10px',
  border: 'none',
  borderRadius: '5px',
};

const Button = () => {
  return <button style={buttonStyle}>Click Me</button>;
};

export default Button;

				
			

Example Combining CSS and Inline Styles

You can also combine both CSS and inline styles if needed

				
					.button {
  border: none;
  border-radius: 5px;
}

				
			
Button.js
				
					import React from 'react';
import './styles.css';

const Button = ({ isPrimary }) => {
  const buttonStyle = {
    backgroundColor: isPrimary ? 'blue' : 'gray',
    color: 'white',
    padding: '10px',
  };

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

export default Button;