Create New Post

React - CSS

In React, you can style your components using CSS in several ways. Here are common approaches:

1. Inline Styles:

You can apply styles directly to your React elements using inline styles. Inline styles are defined as JavaScript objects where keys are CSS properties in camelCase:

import React from 'react';

const MyComponent = () => {
const style = {
color: 'blue',
fontSize: '16px',
// ... other CSS properties
};

return (
<div style={style}>
Hello, I'm styled with inline styles!
</div>
);
};

export default MyComponent;

Keep in mind that inline styles can become unwieldy for complex styles and don't support pseudo-classes or media queries directly.

2. CSS Modules:

CSS Modules allow you to write CSS styles in separate files and import them into your React components. This approach helps keep your styles modular and scoped to specific components:

// styles.module.css
.myComponent {
color: blue;
font-size: 16px;
}

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

const MyComponent = () => {
return (
<div className={styles.myComponent}>
Hello, I'm styled with CSS Modules!
</div>
);
};

export default MyComponent;

3. Styled Components:

The styled-components library allows you to write CSS directly within your JavaScript files using tagged template literals. It promotes the creation of components with encapsulated styles:

import React from 'react';
import styled from 'styled-components';

const StyledDiv = styled.div`
color: blue;
font-size: 16px;
`;

const MyComponent = () => {
return (
<StyledDiv>
Hello, I'm styled with styled-components!
</StyledDiv>
);
};

export default MyComponent;

4. CSS-in-JS Libraries:

Various CSS-in-JS libraries, such as Emotion or JSS, offer additional ways to write styles directly in your JavaScript files. These libraries often provide features like dynamic styles and theming:

// Example with Emotion
import React from 'react';
import { css } from '@emotion/css';

const myComponentStyle = css`
color: blue;
font-size: 16px;
`;

const MyComponent = () => {
return (
<div className={myComponentStyle}>
Hello, I'm styled with Emotion!
</div>
);
};

export default MyComponent;

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

46866