Template Literals & Hooks

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-24
Updated:
2019-08-15
Tags:
React libraries JavaScript css

https://frontendmasters.com/courses/intermediate-react-v2/template-literals-hooks/

Some advantages of having the CSS in the JavaScript files

You can declare local JavaScript variables to put in the CSS via the template literals.

Anything you can do in JavaScript, you can do here with CSS, like adding a hook:

You can manipulate styles via JavaScript.

  //  ****NavBar.js****

// **** 1. import the hook.  ↴
import React, {useState} from "react";
import { Link } from "@reach/router";
import { css, keyframes } from "@emotion/core";
import colors from "./colors";

const Spin = keyframes`
  to {
    transform: rotate(360deg);
  }
`;

const NavBar = () => (
  // **** 2. add a hook.  ↴
  const [padding  setPadding] = useState(15)

  <header
   // **** 3. add click event.  ↴
   onClick={() => setPadding(padding + 15)}
    css={css`
      background-color: ${colors.dark};
       // **** 4. add the dynamic padding.  ↴
      padding: ${paddding}px;
      margin-bottom: 15px;
      border-radius: 0 0 5px 5px;
    `}
  >
    <Link
      css={css`
        &:hover {
          text-decoration: underline;
        }
      `}
      to="/"
    >
      Adopt Me!
    </Link>
    <span
      css={css`
        display: inline-block;
        animation: 1s ${Spin} linear infinite;
        font-size: 60px;
      `}
      aria-label="logo"
      role="img"
    >
      🐩
    </span>
  </header>
);

export default NavBar;

Other advantages

You can delete the NavBar component and the related CSS will be deleted as well.

optimise for deletability !