Functional Components

Our component library currently consists of four top-level components. So far, these have worked well for our landing page, but we don't yet have a way of using these components across different views. Let's change that by turning these components into more flexible functional components that return markup for us to use.

  1. Let's start with the Header component, since that will almost always need to change in response to the current page. The first thing that we should do is export a function that returns the original HTML string. Something like:

    export default function Header() {
      return `
        <div id="header">
          <h1>Welcome to Alex's Savvy Coders Portfolio Project!</h1>
        </div>
      `;
    }

    ...which we can use in our index.js file with:

    document.querySelector("#root").innerHTML = `
      ${Navigation}
      ${Header()} // notice the invocation here
      ${Content}
      ${Footer}
    `;
  2. We should try to think of our components as pure, "dumb" expressions of the state of our application. That application state could eventually get pretty complicated, so let's think of that state as an Object that can eventually store lots of data for us. Let's create that state Object in index.js, then pass that state to our component. In index.js:

    const state = {
      title: "Welcome to Alex's Savvy Coders Portfolio"
    };
    
    document.querySelector("#root").innerHTML = `
          ${Navigation}
          ${Header(state)} // notice the use of state
          ${Content}
          ${Footer}
        `;

    ...and in Header.js:

    export default function Header(state) {
      return `
        <div id="header">
          <h1>${state.title}</h1>
        </div>
      `;
    }
  3. Let's turn every other component into a functional component to be invoked with a state argument (even if we don't actually respond to any part of that state just yet). By the time we're done, our application markup generator should look like:

    document.querySelector("#root").innerHTML = `
      ${Navigation(state)}
      ${Header(state)}
      ${Content(state)}
      ${Footer(state)}
    `;

Last updated

Was this helpful?