Getting Started with Styled Components in React JS and TypeScript

Among the several strategies aimed at increasing the productivity of a development team, the proper organization of the code related to the software being conceived undoubtedly occupies a preponderant place. Over the years, several methods and tools have been created for this purpose. It is important to know them, especially since they can very concretely result in a substantial saving of time, at least in terms of maintenance activities and bug fixing.

In this context, we’ll take a look at how to deploy styled components in a React JS project with TypeScript using the styled-components library. This technique allows components to contain their own styles. This “encapsulation” of styles also involves CSS in JS, using tagged template literals.

Youtube demo:

Github repository: https://github.com/xdth/styled-components-demo

First step: generation of files and installation of project dependencies

Generate React project files with TypeScript

create-react-app styled-components-demo --template typescript


Installation of the styled-components library

yarn add styled-components

Installation of library types

yarn add -D @types/styled-components

Second step: delete unnecessary files

The create-react-app tool generates a few files that we won’t use. They should therefore be deleted.

In the public directory, only the index.html file is needed.
index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <title>dthlabs.com</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

In the src directory, you only need the index.tsx and App.tsx files.

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

App.tsx

import React from 'react';
import GlobalStyle from './styles/global';
import Navbar from './components/Navbar';
import Footer from './components/Footer';

const App: React.FC = () => (
  <>
    <GlobalStyle />
    <Navbar />
    <Footer />
  </>
);

export default App;

Third step: global styles.

The styled-components library allows us to deploy styled components, of course. But, what about overall styles? In order to declare styles affecting the entire site, we will use the createGlobalStyle function. For that effect, we will create a styles directory in src containing a global.ts file.

Global styles:

// src/styles/global.ts
import { createGlobalStyle } from 'styled-components';
import BackgroundImage from '../assets/background.jpg';

export default createGlobalStyle`
  * {
    margin: 0;
    padding: 0;
    outline: 0;
    box-sizing: border-box;
  }

  #root {
    margin: 0 auto;
  }

  html {
    background: url(${BackgroundImage}) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;    
  }
`;

In html we will declare a centralized background image, which will have to be imported from a suitable path, in this case src/assets/background.jpg.

Fourth step: the stylized Navbar component

Also in src, we will have a components directory, where our two stylized components will be placed. In components, we will therefore create two more directories, Navbar and Footer, each having two files: index.tsx where our functional component will be written and styles.tsx for styles.

Navbar component:

// src/components/Navbar/index.tsx
import React from 'react';
import { Container, Logo, Menu, MenuItem } from './styles';

const Navbar: React.FC = () => {
  return (
    <>
      <Container>
        <Logo>dthlabs.com</Logo>
        <Menu>
          <MenuItem>About</MenuItem>
          <MenuItem>Contact</MenuItem>
        </Menu>
      </Container>
    </>
  );
}

export default Navbar;

Navbar styles:

// src/components/Navbar/styles.tsx
import styled from 'styled-components';

export const Container = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  color: #F1F1F1;
`;
export const Logo = styled.div`
  margin-left: 30px;
  font-size: 1.3em;
`;

export const Menu = styled.div`
  display: flex;
  justify-content: flex-end;
`;

export const MenuItem = styled.div`
  margin-right: 30px;
  font-size: 1em;
`;

Fifth step: the stylized Footer component

Finally, here is the last stylized component, following the same structure as the previous one. Component and styles packed together in the component’s folder.

Footer component:

// src/components/Footer/index.tsx
import React from 'react';
import { Container, FooterNav, FooterNavItem } from './styles';

const Footer: React.FC = () => {
  return (
    <>
      <Container>
        <FooterNav>
          <FooterNavItem>Terms and Conditions</FooterNavItem>
          <FooterNavItem>Privacy notice</FooterNavItem>
        </FooterNav>
      </Container>
    </>
  );
}

export default Footer;

Footer styles:

// src/components/Navbar/styles.tsx
import styled from 'styled-components';

export const Container = styled.div`
  position: fixed;
  bottom: 0;
  height: 70px;
  color: #F1F1F1;
  width: 100%;
`;

export const FooterNav = styled.div`
  display: flex;
  justify-content: flex-end;
`;

export const FooterNavItem = styled.div`
  margin: 30px 30px 0px 0px;
  font-size: 1em;
`;

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading Facebook Comments ...
Loading Disqus Comments ...