In React, there are several ways to apply styles to your components. The most common methods include inline styles, CSS-in-JS libraries, and external CSS files. Here’s an overview of each method with examples:
1. Inline Styles
Inline styles are applied directly to the elements via the style attribute. They are written as JavaScript objects.
const InlineStyleComponent = () => {
const divStyle = {
color: ‘blue’,
backgroundColor: ‘lightgray’,
padding: ’10px’,
borderRadius: ‘5px’
};
return (
<div style={divStyle}>
Hello, I am styled with inline styles!
</div>
);
};
export default InlineStyleComponent;
2. Internal Styles (CSS-in-JS)
CSS-in-JS is a technique where CSS is composed using JavaScript. Libraries like styled-components or emotion are commonly used for this purpose.
Using styled-components:
import styled from ‘styled-components’;
const StyledDiv = styled.div`
color: blue;
background-color: lightgray;
padding: 10px;
border-radius: 5px;
`;
const StyledComponent = () => {
return (
<StyledDiv>
Hello, I am styled with styled-components!
</StyledDiv>
);
};
export default StyledComponent;
3. External CSS Files
You can create a separate CSS file and import it into your React component.
styles.css:
color: blue;
background-color: lightgray;
padding: 10px;
border-radius: 5px;
}
Component.js:
import ‘./styles.css’;
const ExternalStyleComponent = () => {
return (
<div className=”styled-div”>
Hello, I am styled with an external CSS file!
</div>
);
};
export default ExternalStyleComponent;
Summary
Inline Styles: Best for quick, dynamic styles that change based on props or state.
Internal Styles (CSS-in-JS): Great for scoped styles, theming, and when using JavaScript to manage CSS.
External CSS Files: Ideal for larger projects where styles are organized in separate files, promoting reusability and separation of concerns.
These methods can be mixed and matched based on the needs of your project.