Skip to Content
React: Up & Running, 2nd Edition
book

React: Up & Running, 2nd Edition

by Stoyan Stefanov
November 2021
Beginner to intermediate
230 pages
4h 49m
English
O'Reilly Media, Inc.
Content preview from React: Up & Running, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

React and React Native - Fourth Edition

React and React Native - Fourth Edition

Adam Boduch, Roy Derks, Mikhail Sakhniuk

Publisher Resources

ISBN: 9781492051459Errata PageSupplemental Content