Adding styled-components
Let's get started building our Todo List! We've set up a simple React app with a header, a description, a button and a few tasks. For our first lesson, we'll add styled-components.
Adding styled-components in package.json
If you click on package.json, you'll see that we've added a line in our dependencies
to include version 6 of styled-components
. Our sandbox will automatically install dependencies as you add them. If you were working locally, you'd use the yarn
command to install styled-components. Check out the official installation instructions for more details.
Using styled-components to style a header
Now that we've added the styled-components dependency, let's go to our App.js
and import the library using import styled
. This is the main function used to create styled-components in our React app. You can see that we've used this command to style an <h1>
. The styled.h1
is immediately followed by a template literal to open up a multi-line string that we can write normal CSS inside of. Here we are overwriting the font-size
property of the h1
for our app.
Your mission
Try using styled-components to style a button, paragraph and Task elements. Use good variable names that correspond to element's purpose in our app.
// Import styled-components into our app import styled from "styled-components"; // Using styled-components to style an h1 const Header = styled.h1` font-size: 32px; `; const tasks = [ { name: "Swab the deck", id: 1 }, { name: "Find treasure", id: 2 }, { name: "Set sail", id: 3 }, ]; function Task({ name, onClick }) { return <div onClick={onClick}> {name} </div>; } export default function App() { return ( <div> <Header> 🏴☠️ Captain's Tasks </Header> <p> Manage the daily jobs at sea </p> <button onClick={() => alert("Adding task")}>Add Task</button> {tasks.map(({ name, id }, i) => ( <Task key={`task-${id}`} name={name} /> ))} </div> ); }