React Styling Options:
1. Inline CSS
- Where? Directly in JSX elements.
- How? By using the style attribute with an object of style properties in camelCase.
- Scope? Local to the specific JSX element.
- Based On? CSS.
const element = <div style={{ color: 'blue', fontSize: '14px' }}>
Hello World!
</div>;
2. CSS or SASS file
- Where? External .css or .sass/.scss files.
- How? By linking CSS classes, IDs, etc., in these files to JSX elements.
- Scope? Global, affecting the entire application.
- Based On? CSS/SASS.
/* styles.css */
.myClass {
color: red;
}
import './styles.css';
const element = <div className='myClass'>Hello World</div>;
3. CSS Modules
- Where? A separate .module.css file for each component.
- How? By importing and using class names as objects.
- Scope? Component-specific, to isolate styles.
- Based On? CSS.
领英推荐
/* MyComponent.module.css */
.myClass {
color: green;
}
import styles from './MyComponent.module.css';
const MyComponent = () => <div className={styles.myClass}>
Hello World
</div>;
4. CSS in JS
- Where? Within JavaScript or component files.
- How? By creating styles using JavaScript objects or functions.
- Scope? Local to the component.
- Based On? JavaScript.
import styled from 'styled-components';
const StyledDiv = styled.div`
color: purple;
`;
const MyComponent = () => <StyledDiv>Hello World</StyledDiv>;
5. Utility-First Classes (e.g., Tailwind CSS)
- Where? Directly in JSX elements.
- How? By using utility classes for styling.
- Scope? Global, but used locally in JSX elements.
- Based On? CSS.
const element = <div className='text-blue-500 font-bold'>
Hello World
</div>;
6. UI Libraries (e.g., MUI, Chakra UI, Mantine)
- Where? Through components provided by the library.
- How? By using pre-styled components or customizing them through library-specific theming systems.
- Scope? Depends on the usage within components.
- Based On? Library-specific styles, often using CSS in JS.
import { Button } from '@mui/material';
const MyComponent = () => <Button color="primary">
Hello World
</Button>;