After setting up the boilerplate with create-react-app, it's great to get some css-in-js with styled-components. Here's how:
- Open a terminal and go to your create-react-project (or similar) by running
cd my-project-path - Start the project by running
yarn startand make sure it opens tohttp://localhost:3000or similar - Open a new terminal and run
yarn add styled-components - Open your project in VS Code and find the
srcfolder - Create a new folder and file inside
srcby clickingNew filethen writingcomponents/MyFirstComponent.js - Open the new file
- 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
- Now that the file is created, let's check the flow of create-react-app.
- The file
public/index.htmlis the base web page, it has a div with id root in the body<div id="root"></div> - React injects the content from
src/index.jsinto<div id="root"></div> - is imported from App.js and added inside index.js
- 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;
- That's it!