Book Image

Learn React with TypeScript - Second Edition

By : Carl Rippon
4.4 (8)
Book Image

Learn React with TypeScript - Second Edition

4.4 (8)
By: Carl Rippon

Overview of this book

Reading, navigating, and debugging a large frontend codebase is a major issue faced by frontend developers. This book is designed to help web developers like you learn about ReactJS and TypeScript, both of which power large-scale apps for many organizations. This second edition of Learn React with TypeScript is updated, enhanced, and improved to cover new features of React 18 including hooks, state management libraries, and features of TypeScript 4. The book will enable you to create well-structured and reusable React components that are easy to read and maintain, leveraging modern design patterns. You’ll be able to ensure that all your components are type-safe, making the most of TypeScript features, including some advanced types. You’ll also learn how to manage complex states using Redux and how to interact with a GraphQL web API. Finally, you’ll discover how to write robust unit tests for React components using Jest. By the end of the book, you’ll be well-equipped to use both React and TypeScript.
Table of Contents (19 chapters)
1
Part 1: Introduction
6
Part 2: App Fundamentals
10
Part 3: Data
14
Part 4: Advanced React

Using props

Currently, the alert component is pretty inflexible. For example, the alert consumer can’t change the heading or the message. At the moment, the heading or the message needs to be changed within Alert itself. Props solve this problem, and we will learn about them in this section.

Note

Props is short for properties. The React community often refers to them as props, so we will do so in this book.

Understanding props

props is an optional parameter that is passed into a React component. This parameter is an object containing the properties of our choice. The following code snippet shows a props parameter in a ContactDetails component:

function ContactDetails(props) {
  console.log(props.name);
  console.log(props.email);
  ...
}

The props parameter contains the name and email properties in the preceding code snippet.

Note

The parameter doesn’t have to be named props, but it is common practice.

Props are passed into a component in JSX as attributes. The prop names must match what is defined in the component. Here is an example of passing props into the preceding ContactDetails component:

<ContactDetails name="Fred" email="[email protected]" />

So, props make the component output flexible. Consumers of the component can pass appropriate props into the component to get the desired output.

Next, we will add some props to the alert component we have been working on.

Adding props to the alert component

In the CodeSandbox project, carry out the following steps to add props to the alert component to make it more flexible:

  1. Open alert.js and add a props parameter to the function:
    export function Alert(props) {
      ...
    }
  2. We will define the following properties for the alert:
    • type: This will either be "information" or "warning" and will determine the icon in the alert.
    • heading: This will determine the heading of the alert.
    • children: This will determine the content of the alert. The children prop is actually a special prop used for the main content of components.

Update the alert component’s JSX to use the props as follows:

export function Alert(props) {
  return (
    <div>
      <div>
        <span
          role="img"
          aria-label={
            props.type === "warning"
              ? "Warning"
              : "Information"
          }
        >
          {props.type === "warning" ? "" : "ℹ"}
        </span>
        <span>{props.heading}</span>
      </div>
      <div>{props.children}</div>
    </div>
  );
}

Notice that the Browser panel now displays nothing other than an information icon (this is an information emoji); this is because the App component isn’t passing any props to Alert yet:

Figure 1.3 – The alert component only showing the information icon

Figure 1.3 – The alert component only showing the information icon

  1. Open App.js and update the Alert component in the JSX to pass in props as follows:
    export default function App() {
      return (
        <div className="App">
          <Alert type="information" heading="Success">
            Everything is really good!
          </Alert>
        </div>
      );
    }

Notice that the Alert component is no longer self-closing so that Everything is really good! can be passed into its content. The content is passed to the children prop.

The Browser panel now displays the configured alert component:

Figure 1.4 – The configured alert component in the browser panel

Figure 1.4 – The configured alert component in the browser panel

  1. We can clean up the alert component code a little by destructuring the props parameter.

Note

Destructuring is a JavaScript feature that allows properties to be unpacked from an object. For more information, see the following link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment.

Open Alert.js again, destructure the function parameter, and use the unpacked props as follows:

export function Alert({ type, heading, children }) {
  return (
    <div>
      <div>
        <span
          role="img"
          aria-label={
            type === "warning" ? "Warning" :               "Information"
          }
        >
          {type === "warning" ? "⚠" : "ℹ"}
        </span>
        <span>{heading}</span>
      </div>
      <div>{children}</div>
    </div>
  );
}

This is a little cleaner because we use the unpacked props directly rather than having to reference them through the props parameter.

  1. We want the type prop to default to "information". Define this default as follows:
    export function Alert({
      type = "information",
      heading,
      children
    }) {
      ...
    }

That completes the implementation of the props in the alert component for now. Here’s a quick recap on props:

  • Props allow a component to be configured by the consuming JSX and are passed as JSX attributes
  • Props are received in the component definition in an object parameter and can then be used in its JSX

Next, we will continue to make the alert component more sophisticated by allowing it to be closed by the user.