React component is the building block of a React application. Let us learn how to create a new React component and the features of React components in this chapter.
A React component represents a small chunk of user interface in a webpage. The primary job of a React component is to render its user interface and update it whenever its internal state is changed. In addition to rendering the UI, it manages the events belongs to its user interface. To summarize, React component provides below functionalities.
React component accomplish these feature using three concepts −
Properties − Enables the component to receive input.
Events − Enable the component to manage DOM events and end-user interaction.
State − Enable the component to stay stateful. Stateful component updates its UI with respect to its state.
Let us learn all the concept one-by-one in the upcoming chapters.
React library has two component types. The types are categorized based on the way it is being created.
The core difference between function and class component are −
Function components are very minimal in nature. Its only requirement is to return a React element.
The same functionality can be done using ES6 class component with little extra coding.
Class components supports state management out of the box whereas function components does not support state management. But, React provides a hook, useState() for the function components to maintain its state.
Class component have a life cycle and access to each life cycle events through dedicated callback apis. Function component does not have life cycle. Again, React provides a hook, useEffect() for the function component to access different stages of the component.
Let us create a new React component (in our expense-manager app), ExpenseEntryItem to showcase an expense entry item. Expense entry item consists of name, amount, date and category. The object representation of the expense entry item is −
Open expense-manager application in your favorite editor.
Next, create a file, ExpenseEntryItem.css under src/components folder to style our component.
Next, create a file, ExpenseEntryItem.js under src/components folder by extending React.Component.
Next, create a method render inside the ExpenseEntryItem class.
Next, create the user interface using JSX and return it from render method.
Next, specify the component as default export class.
Now, we successfully created our first React component. Let us use our newly created component in index.js.
The same functionality can be done in a webpage using CDN as shown below −
Next, serve the application using npm command.
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
The above ExpenseEntryItem can be rewritten in function as specified below −
Here, we just included the render functionality and it is enough to create a simple React component.