Chapter 3. Create Your First React Component

In the previous chapter, we learned how to create React elements and how to use them to render the HTML markup. You've seen how easy it is to produce React elements using JSX. At this point, you know enough about React in order to create the static web pages that we discussed in Chapter 2, Create Your First React Element. However, I bet that's not the reason why you've decided to learn React. You don't want to just build websites made of static HTML elements. You want to build interactive user interfaces that react to user and server events. What does it mean to react to an event? How can a static HTML element react? How can a React element react? In this chapter, we'll answer these questions and many other questions while introducing ourselves to React components.

Stateless versus stateful

To react means to switch from one state to another. This means that you need to have a state in the first place and the ability to change that state. Have we mentioned a state or the ability to change that state in React elements? No. They are stateless. Their sole purpose is to construct and render virtual DOM elements. In fact, we want them to render in the exact same way, given that we provide them the exact same set of parameters. We want them to be consistent because it makes it easy for us to reason about them. That's one of the key benefits of using the React library—the ease of reasoning how our web application works.

How can we add a state to our stateless React elements? If we can't encapsulate a state in React elements, then we should encapsulate React elements in something that already has a state. Think of a simple state machine that represents a user interface. Every user action triggers a change of a state in that state machine. Every state is represented by a different React element. In the React library, this state machine is called a React Component.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.55.151