React CSS Styling
There are three ways to style in React:
- Inline Styling
- CSS Stylesheets
- CSS Modules
Inline Styling
To inline style an element, we can make a JavaScript Object, like this:
const App = () => {
return (
<>
<h1 style={{ backgroundColor: "purple" }}>CodeWithHarry</h1>
</>
);
}
In this, the first curly brace is to write JavaScript and the second is to make a JavaScript object. We can also write it like:
const App = () => {
const h1Style = {
backgroundColor: 'purple',
color: 'white'
}
return (
<>
<h1 style={h1Style}>CodeWithHarry</h1>
</>
);
}
Note: CSS property names must be camelCase. background-color
would be backgroundColor
.
CSS Stylesheets
You can save the whole CSS in a separate file with the file extension .css
and import it into your application.
App.css
body {
background-color: 'purple';
color: 'white';
}
Here we are writing CSS, so we don't need to make a JS Object or do it in camelCase.
Index.js
Just import it like this:
import './App.css'
CSS Modules
In this, you don't have to worry about name conflicts as it is component-specific. The CSS is available only for the file in which it is imported.
Make a file with the extension .module.css
, for example: index.module.css
Make a new file index.module.css
and insert some CSS into it, like this:
.button {
background-color: 'purple';
color: 'white';
}
Import it in the component like this:
import styles from './index.module.css';
const Home = () => {
return (
<button className={styles.button}>Click me!</button>
)
};
export default Home;