In React, there are several ways to apply CSS to your components, each with its own advantages. Here are the most common methods:
1. Inline Styles
Inline styles are defined directly within the component using the style attribute. The styles are written as an object, where the property names are camelCased versions of the CSS properties.
import React from 'react';
//MyComponent.jsx
export default function MyComponent() {
const style = {
color: 'green',
backgroundColor: 'yellow',
padding: '5px',
borderRadius: '3px'
};
return <div style={style}>Hello World text with inline styles!</div>;
}
2. CSS Stylesheets
You can use traditional CSS stylesheets by importing them into your React component. This is the most straightforward way to style your components.
CSS File (styles.css)
.my-class {
color: 'green',
backgroundColor: 'yellow',
padding: '5px',
borderRadius: '3px'
}
React Component
import React from 'react';
import './styles.css';
//MyComponent.jsx
export default function MyComponent() {
return <div className="my-class">This is styled with a CSS stylesheet!</div>;
}
3. CSS Modules
CSS Modules allow you to write CSS that is scoped locally to the component. This prevents conflicts with other styles and ensures that styles are only applied to the component they are intended for.
CSS Module (styles.module.css)
.my-class {
color: 'green',
backgroundColor: 'yellow',
padding: '5px',
borderRadius: '3px'
}
React Component
//CSSModulesComponent.jsx
import React from 'react';
import styles from './styles.module.css';
export default function CSSModulesComponent() {
return <div className={styles.myClass}>This is styled with CSS Modules!</div>;
}
apply css in reactjs – Interview Questions
Q 1: How many ways can CSS be applied in React?
Q 2: How do you apply inline styles in React?
Q 3: What are CSS Modules?
Q 4: Can we use normal CSS files?
Q 5: Which method is best?
Reactjs apply css in reactjs – Objective Questions (MCQs)
Q1. Which of the following is NOT a valid way to apply CSS in ReactJS?
Q2. How do you apply inline CSS in React?
Q3. What is the correct syntax to import an external CSS file in a React component?
Q4. What is the main purpose of CSS Modules in React?
Q5. Which of the following applies a class correctly in JSX?