Skip to content

Instantly share code, notes, and snippets.

@SebastianUdden
Last active December 6, 2020 09:41
Show Gist options
  • Select an option

  • Save SebastianUdden/996d7a03a6687dc3f0059a3e538c3c23 to your computer and use it in GitHub Desktop.

Select an option

Save SebastianUdden/996d7a03a6687dc3f0059a3e538c3c23 to your computer and use it in GitHub Desktop.
Create a basic styled-component in React

Go to gists overview

Create a basic styled component

After setting up the boilerplate with create-react-app, it's great to get some css-in-js with styled-components. Here's how:

  1. Open a terminal and go to your create-react-project (or similar) by running cd my-project-path
  2. Start the project by running yarn start and make sure it opens to http://localhost:3000 or similar
  3. Open a new terminal and run yarn add styled-components
  4. Open your project in VS Code and find the src folder
  5. Create a new folder and file inside src by clicking New file then writing components/MyFirstComponent.js
  6. Open the new file
  7. Add imports, a basic styled component and a basic react component that uses the styled component
import React from "react"
import styled from "styled-components"

const StyledExample = styled.h1`
  border: 1px solid red;
`;

const MyFirstComponent = () => { 
  return (<StyledExample>A header with red border</StyledExample>)
}

export default MyFirstComponent
  1. Now that the file is created, let's check the flow of create-react-app.
  2. The file public/index.html is the base web page, it has a div with id root in the body <div id="root"></div>
  3. React injects the content from src/index.js into <div id="root"></div>
  4. is imported from App.js and added inside index.js
  5. Now we will do the same thing with our component by adding an import of MyFirstComponent then using it inside the return statement of App like this
import './App.css';
import MyFirstComponent from "./components/MyFirstComponent";

function App() {
  return (
    <MyFirstComponent />
  );
}

export default App;
  1. That's it!

What's next?

Make your React app full width and height

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment