Styling React Components
Let's learn how to style our React components with CSS!
There are many ways to do this. Over on the right we'll see two examples: inline-styling with the style
attribute and traditional CSS class styling with the className
attribute.
Inline styling with the style attribute
To style a React component with the style attribute, you simply include the style
prop on a React component. This prop accepts an object with keys and values mapping to the CSS property and value. These map nearly identically to the classic CSS properties and values, but React requires you to camelCase attributes typically hyphonated. For example, box-shadow
is now boxShadow
.
Styling with the className prop
You can also use the className
prop as though it was the HTML class
attribute to add a CSS class name to that component. Both of the approaches we're discussing here are patterns already in HTML and CSS so they behave nearly the same- a class added to a React component will behave the same way as though you added it to the associated HTML element. You can see in our example on the right, we've added a className="add-explorer-button"
- you can find that style defined in styles.css
.
Both of these approaches work but there have been improvements made in the React ecosystem. React School will recommend a styled-component
approach described in the next lesson. This will forgo any CSS classNames to remember or object key value syntax. We believe it is the easiest way to get started with styling React Components.
const crew = [ { name: "Joe", id: uniqueId() }, { name: "Mark", id: uniqueId() }, { name: "Bob", id: uniqueId() }, ]; function User({ name, onClick }) { // inline style here. return ( <div style={{ border: "1px solid blue", maxWidth: "100px", padding: "5px", margin: "5px 0px", boxShadow: "0px 0px 5px black", borderRadius: "8px", }} onClick={onClick} > {" "} {name}{" "} </div> ); } function uniqueId() { return Math.floor(Math.random() * 10000000); } export default function App() { function sayHello(name) { alert("hello, " + name); } return ( <div> <h1> 🏴☠️ The Captain's Crew </h1> <p> Tiny User Management System (TUMS) </p> <h2> Explorers </h2> {/* Inline style here */} <button className="add-explorer-button" style={{ fontSize: "20px", marginBottom: "10px" }} onClick={() => alert("Adding explorer")} > Add Explorer </button> {crew.map(({ name, id }, i) => ( <User key={`task-${id}`} name={name} onClick={() => { sayHello(name); }} /> ))} </div> ); }