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:
constMyComponent=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:
constMyComponent=function(){returnReact.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.
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.
Read now
Unlock full access