• 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!
Gal Normal

Ready to make your components look fabulous?

Geek Curious

Absolutely! How do we style JSX components?

Gal Happy

It's simple! In JSX, you can apply inline styles or use external stylesheets, just like with regular HTML!

  • Inline Styles
Gal Pleased

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>;
Geek Happy

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!

Gal Happy

Exactly! Now, let's move on to external stylesheets!

  • External Stylesheets
Gal Pleased

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>;
Geek Happy

Oh, so we use className instead of class and import the CSS file like a module!

Gal Happy

Exactly! You can combine both inline and external styles to make your components shine! ✨

  • Hilarious Styling Example
Geek Curious

Can we have a hilarious styling example?

Gal Pleased

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;
Geek Happy

Haha, that's so funny! Styling in JSX is awesome and versatile!

Gal Happy

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! 🎨