Instead of importing CSS stylesheets, another way to implement CSS to your React Components is by using Style Attributes. Style attributes are attributes that are used to add basic CSS styling, except their built as objects. In them we make object properties that have the same name as CSS properties but with camel case, and their value is one that's available on CSS as well. In the example below, we made a style attribute for our header with a color object with a string value of red, making the h1's color red. The Style attributes value and it's object property uses brackets {}
const App = () => {
return (<h1 style={{color: 'red'}}>I'm Red!</h1>);
}
var root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<App />);
root.render(<App />);
//It renders a header with a red color
Storing Objects
Since the value of a style attribute is an object property, a cool way to organize your properties is storing them all in an object variable. In the example below we made a styles object that contains CSS object properties that we can all use by calling the object at the header elements style attribute.
const App = () => {
//Object Properties in the style varaible
const styles = {
textDecoration: "underline",
color: "magenta",
padding: '10' + 'px',
backgroundColor: 'black',
borderRadius: '5px'
}
//Calling all the properties in the header
return (<h1 style={styles}>I'm Magenta!</h1>);
}
var root = ReactDOM.createRoot(document.querySelector('#app'));
root.render(<App />);
Overall using style attributes and their object properties can help you lower your CSS storage size and style your React Components without the need for stylesheets at all. To me it's like using a style attribute in your HTML file but with JSX and JS fundamentals, let me know what you think about them! Have a great day/night 👋.
Top comments (0)