AI Hints
Home›React Tutorial›Styling and Practice
React · Lesson 16 of 120

Styling

ClassName and style.

⏱ 2 min read▶ Video at 11:44🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

There are two everyday ways to style React components. Class names that point to CSS rules. And the style prop, which takes a JavaScript object.

  • className
  • style={{ }}
  • Two ways

Both ways

The CSS file defines a sale class. The first card uses class name, and adds sale only when needed. The second uses the style prop, with camel case properties, and a colour chosen in code. Run it.

App.jsxjsx
import "./shop.css";

function Card({ model, onSale }) {
  return <div className={onSale ? "card sale" : "card"}>{model}</div>;
}

export default function App() {
  const stock = 0;
  return (
    <>
      <Card model="Trail 500" onSale />
      <Card model="City 200" />
      <p style={{ color: stock > 0 ? "green" : "crimson", fontWeight: 700 }}>
        {stock > 0 ? "In stock" : "Out of stock"}
      </p>
    </>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses shop.css
.card{padding:14px;border:2px solid #ddd;border-radius:12px;margin:8px 0;background:#fff}
.sale{border-color:#e11d48;background:#fff1f2}
.sale::after{content:" SALE";color:#e11d48;font-weight:800}

Other options

Bigger projects often use CSS modules, which keep class names local to one component. Or utility classes, like Tailwind. Or a CSS in JS library. All work well with React.

keyvalue
CSS filesclassName
CSS moduleslocal names
Tailwindutility classes
style propdynamic values

Summary

Use class name for CSS classes, and the style prop for dynamic values. Next, practice with a product card.

Key takeaways
  • className
  • style={{...}}
  • camelCase
Next up: Practice: A Product Card — props together