Archives

gravatar

Where HTML elements have attributes, React components have props

 A prop is any data passed into a React component. React props are comparable to HTML attributes. 

Where HTML elements have attributes, React components have props. 

Props are written inside component calls, and use the same syntax as HTML attributes — prop="value".  

In React, dataflow is unidirectional: props can only be passed from Parent components down to Child components; and props are read-only.

Let’s open index.js and give our <App/> call its first prop.

Add a prop of subject to the <App/> component call, with a value of Clarice. When you are done, your code should look something like this:

ReactDOM.render(<App subject="Clarice" />, document.getElementById('root'));

Back in App.js, let's revisit the App function itself, which reads like this (with the return statement shortened for brevity):

function App() {
  const subject = "React";
  return (
    // return statement
  );
}

Change the signature of the App function so that it accepts props as a parameter, and delete the subject const. 

Just like any other function parameter, you can put props in a console.log() to print it to your browser's console. Go ahead and do that before the return statement, like so:

function App(props) {
  console.log(props);
  return (
    // return statement
  );
}

Save your file and check your browser's JavaScript console. You should see something like this logged:

Object { subject: "Clarice" }

The object property subject corresponds to the subject prop we added to our <App /> component call, and the string Clarice corresponds to its value. Component props in React are always collected into objects in this fashion.

Now that subject is one of our props, let's utilize it in App.js

Change the subject constant so that, instead of defining it as the string React, you are reading the value of props.subject. You can also delete your console.log() if you want.

function App(props) {
  const subject = props.subject;
  return (
    // return statement
  );
}

When you save, the app should now greet you with "Hello, Clarice!". If you return to index.js, edit the value of subject, and save, your text will change.

gravatar

Import statements In React

 

In React, a component is a reusable module that renders a part of our app. These parts can be big or small, but they are usually clearly defined: they serve a single, obvious purpose.

Let's open src/App.js, since our browser is prompting us to edit it. This file contains our first component, App, and a few other lines of code:

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
export default App;

The App.js file consists of three main parts: some import statements at the top, the App component in the middle, and an export statement at the bottom. Most React components follow this pattern.

Import statements

The import statements at the top of the file allow App.js to use code that has been defined elsewhere. Let's look at these statements more closely.

import React from 'react';
import logo from './logo.svg';
import './App.css';

The first statement imports the React library itself. Because React turns the JSX we write into React.createElement(), all React components must import the React module. If you skip this step, your application will produce an error.

The second statement imports a logo from './logo.svg'. Note the use of ./ at the beginning of the path, and the .svg extension at the end — these tell us that the file is local and that it is not a JavaScript file. Indeed, the logo.svg file lives in our source directory.

We don't write a path or extension when importing the React module — this is not a local file; instead, it is listed as a dependency in our package.json file. Be careful of this distinction as you work through this lesson!

The third statement imports the CSS related to our App component. Note that there is no variable name and no from directive. 

This particular import syntax is not native to JavaScript module syntax — it comes from Webpack, the tool create-react-app uses to bundle all our JavaScript files together and serve them to the browser.

gravatar

Create applications with frameworks

Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience.


Domain-specific languages

All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications.

In particular, React has popularized the use of JSX for writing its components, while Ember utilizes Handlebars. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI.

DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. Transformation is an extra step in the development process, but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. 

While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks.


Writing components

As mentioned in the previous chapter, most frameworks have some kind of component model. React components be written with JSX

Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup.

The code snippets in the rest of this section will use React as an example, and are written with JSX.

Properties

Properties, or props, are external data that a component needs in order to render. 

Suppose you're building a website for an online magazine, and you need to be sure that each contributing writer gets credit for their work. 

You might create an AuthorCredit component to go with each article. This component needs to display a portrait of the author and a short byline about them. 

In order to know what image to render, and what byline to print, AuthorCredit needs to accept some props.

A React representation of this AuthorCredit component might look something like this:

function AuthorCredit(props) {
  return (
    <figure>
      <img src={props.src} alt={props.alt} />
      <figcaption>{props.byline}</figcaption>
    </figure>
  );
}

{props.src}{props.alt}, and {props.byline} represent where our props will be inserted into the component. To render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component):

<AuthorCredit
  src="./assets/zelda.png"
  alt="Portrait of Zelda Schiff"
  byline="Zelda Schiff is editor-in-chief of the Library Times."
/>

This will ultimately render the following <figure> element in the browser, with its structure as defined in the AuthorCredit component, and its content as defined in the props included on the AuthorCredit component call:

<figure>
  <img
    src="assets/zelda.png"
    alt="Portrait of Zelda Schiff"
  >
  <figcaption>
    Zelda Schiff is editor-in-chief of the Library Times.
  </figcaption>
</figure>

State

We talked about the concept of state in the previous chapter — a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. 

This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered.

As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own count state, and could be written like this:

function CounterButton() {
  const [count] = useState(0);
  return (
    <button>Clicked {count} times</button>
  );
}

useState() is a React hook which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser:

<button>Clicked 0 times</button>

The useState() call keeps track of the count value in a robust way across the app, without you needing to write code to do that yourself.

Events

In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. 

Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events.

In React, listening for the click event requires a special property, onClick. Let’s update our CounterButton code from above to allow it to count clicks:

function CounterButton() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
  );
}

In this version we are using additional useState() functionality to create a special setCount() function, which we can invoke to update the value of count

We call this function on line 4, and set count to whatever its current value is, plus one.

Styling components

Each framework offers a way to define styles for your components — or for the application as a whole. Although each framework’s approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. 

With the addition of some helper modules, you can style your framework apps in Sass or Less, or transpile your CSS stylesheets with PostCSS.

Handling dependencies

All major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels. 

As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard JavaScript module syntax, or at least something similar.

Components in components

One key benefit of component-based UI architecture is that components can be composed together. 

Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. 

Each framework allows you to write components that utilize (and thus depend on) other components.

For example, our AuthorCredit React component might be utilized inside an Article component. That means that Article would need to import AuthorCredit.

import AuthorCredit from "./components/AuthorCredit";

Once that’s done, AuthorCredit could be used inside the Article component like this:

  ...

<AuthorCredit />

  ...

Dependency injection

Real-world applications can often involve component structures with multiple levels of nesting. An AuthorCredit component nested many levels deep might, for some reason, need data from the very root level of our application.

Let's say that the magazine site we're building is structured like this:

<App>
  <Home>
    <Article>
      <AuthorCredit {/* props */} />
    </Article>
  </Home>
</App>

Our App component has data that our AuthorCredit component needs. We could rewrite Home and Article so that they know to pass props down, but this could get tedious if there are many, many levels between the origin and destination of our data.

It's also excessive: Home and Article don’t actually make use of the author's portrait or byline, but if we want to get that information into the AuthorCredit, we will need to change Home and Article to accommodate it.

The problem of passing data through many layers of components is called prop drilling, and it’s not ideal for large applications.

To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. 

Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same.

Lifecycle

In the context of a framework, a component’s lifecycle is a collection of phases a component goes through from the time it is appended to the DOM and then rendered by the browser (often called mounting) to the time that it is removed from the DOM (often called unmounting).

Each framework names these lifecycle phases differently, and not all give developers access to the same phases. 

All of the frameworks follow the same general model: they allow developers to perform certain actions when the component mounts, when it renders, when it unmounts, and at many phases in between these.

The render phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there.

This diagram of a React component's lifecycle offers a general overview of the concept.

Rendering elements

Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. 

All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. 

Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they’re known for.

The Virtual DOM is an approach whereby information about your browser's DOM is stored in JavaScript memory. 

Your application updates this copy of the DOM, then compares it to the "real" DOM — the DOM that is actually rendered for your users — in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. 

Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering.

Routing

The most essential feature of the web is that it allows users to navigate from one page to another – it is, after all, a network of interlinked documents. 

When you follow a link on this very website, your browser communicates with a server and fetches new content to display for you. As it does so, the URL in your address bar changes.

 You can save this new URL and come back to the page later on, or share it with others so they can easily find the same page. Your browser remembers your navigation history and allows you to navigate back and forth, too. This is called server-side routing.

Modern web applications typically do not fetch and render new HTML files — they load a single HTML shell, and continually update the DOM inside it (referred to as single page apps, or SPAs) without navigating users to new addresses on the web. 

Each new pseudo-webpage is usually called a view, and by default, no routing is done.

When an SPA is complex enough, and renders enough unique views, it's important to bring routing functionality into your application. 

People are used to being able to link to specific pages in an application, travel forward and backward in their navigation history, etc., and their experience suffers when these standard web features are broken. When routing is handled by a client application in this fashion, it is aptly called client-side routing.

It's possible to make a router using the native capabilities of JavaScript and the browser, but popular, actively developed frameworks have companion libraries that make routing a more intuitive part of the development process.

Routing is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications.

Testing

All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. 

Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools.

Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike.

Testing Library is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular.  The Ember docs cover the testing of Ember apps.

Here’s a quick test for our CounterButton written with the help of React Testing Library — it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times:

import React from "react";
import { render, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";

import CounterButton from "./CounterButton";

it("renders a semantic with an initial state of 0", () => {
  const { getByRole } = render(<CounterButton />);
  const btn = getByRole("button");

  expect(btn).toBeInTheDocument();
  expect(btn).toHaveTextContent("Clicked 0 times");
});

it("Increments the count when clicked", () => {
  const { getByRole } = render(<CounterButton />);
  const btn = getByRole("button");

  fireEvent.click(btn);
  expect(btn).toHaveTextContent("Clicked 1 times");

  fireEvent.click(btn);
  expect(btn).toHaveTextContent("Clicked 2 times");
});