- Introduction
We’ve been learning about JSX and React Elements, and now it’s time to add some style to our components! In this section, we’ll cover Styling in JSX. Let’s dive in with the help of our geeky duo, Geek and Gal!
Ready to make your components look fabulous?
Absolutely! How do we style JSX components?
It's simple! In JSX, you can apply inline styles or use external stylesheets, just like with regular HTML!
To apply inline styles, create a JavaScript object with the styles and pass it to the
style
attribute of the JSX element. Remember to use camelCase for property names!
const divStyle = {
backgroundColor: 'lightblue',
padding: '20px',
borderRadius: '10px'
};
const element = <div style={divStyle}>Hello, world!</div>;
Got it! So we create a style object and use camelCase for properties. Then, we pass the object to the
style
attribute of the JSX element!
Exactly! Now, let's move on to external stylesheets!
Using external stylesheets is super easy! Just import the CSS file and use the class names as usual. Just make sure to use the
className
attribute instead of
class
.
// Import the CSS file
import './App.css';
// Use the 'container' class from the CSS file
const element = <div className="container">Hello, world!</div>;
Oh, so we use
className
instead of
class
and import the CSS file like a module!
Exactly! You can combine both inline and external styles to make your components shine! ✨
- Hilarious Styling Example
Can we have a hilarious styling example?
Sure! Let's create a spinning rainbow text using both inline styles and external stylesheets!
// App.css
.rainbow-text {
font-size: 24px;
animation: rainbow 5s linear infinite;
}
// App.js
import React from 'react';
import './App.css';
const spinStyle = {
display: 'inline-block',
transformOrigin: 'center',
animation: 'spin 3s linear infinite'
};
const App = () => {
return (
<h1 className="rainbow-text" style={spinStyle}>
Spinning Rainbow Text! 🌈
</h1>
);
};
export default App;
Haha, that's so funny! Styling in JSX is awesome and versatile!
I'm glad you're having fun! Keep experimenting and make your components stylish! 😄
- Conclusion
Styling in JSX is flexible and allows you to use both inline styles and external stylesheets. Just remember to use camelCase for inline styles and the
className
attribute for class names. Have fun creating stunning components! 🎨