React allows us to bind CSS styles in multiple ways.
Some of the popular methods are:
- Inlining the CSS styles with objects
- Binding objects to style which already contains the CSS styles
- Object or styles binding based on conditions
- Binding object from another file containing a list of styles
Here we’ll see how we can bind CSS styles from an object directly:
const App = () => {
const fontStyles = {
color: "#ff0000",
fontSize: "1.2rem",
fontWeight: "bold",
fontStyle: "italic"
};
return (
<div className="App">
<h1 style={fontStyles}>Some styled title!</h1>
</div>
);
};
export default App;
Code language: JavaScript (javascript)
In the above code, we’re binding the CSS styles named fontStyles on line 11. We’ve declared this fontStyle object on line 2.
Of course, we can also import and bind style objects from other files. Consider this file named styles.js containing the following code:
export const fontStyles = {
color: "#ff0000",
fontSize: "1.2rem",
fontWeight: "bold",
fontStyle: "italic"
};
Code language: JavaScript (javascript)
We can import the above styles into our component and use them as needed:
import "./styles.css";
import { fontStyles } from "./styles";
const App = () => {
return (
<div className="App">
<h1 style={fontStyles}>Some styled title!</h1>
</div>
);
};
export default App;
Code language: JavaScript (javascript)
On line 2 we’ve imported the fontStyle object from the file and on line 7, we’ve bound the object to the style.
Here are the demo links for the above code: