Chapter 2. The Life of a Component

Now that you know how to use the ready-made DOM components, it’s time to learn how to make some of your own.

There are two ways to define a custom component, both accomplishing the same result but using different syntax:

  • Using a function (components created this way are referred to as function components)

  • Using a class that extends React.Component (commonly referred to as class components)

A Custom Function Component

Here’s an example of a function component:

const MyComponent = function() {
  return 'I am so custom';
};

But wait, this is just a function! Yes, the custom component is just a function that returns the UI that you want. In this case, the UI is only text but you’ll often need a little bit more, most likely a composition of other components. Here’s an example of using a span to wrap the text:

const MyComponent = function() {
  return React.createElement('span', null, 'I am so custom');
};

Using your shiny new component in an application is similar to using the DOM components from Chapter 1, except you call the function that defines the component:

ReactDOM.render(
  MyComponent(),
  document.getElementById('app')
);

The result of rendering your custom component is shown in Figure 2-1.

rur2 0201
Figure 2-1. Your first custom component (02.01.custom-functional.html in the book’s repository)

A JSX Version

The same example using JSX will look a ...

Get React: Up & Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.