Components and Props
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
Two types of Components
- Class component.
- Functional component.
Functional component
Simple functional component example is shown below
Class Components
Example of class component
The simplest way to define a component is to write a JavaScript function :
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.
You can also use an ES6 class to define a component :
Rendering a Component
Previously, we only encountered React elements that represent DOM tags :
However, elements can also represent user-defined components:
When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object. We call this object “props”.
For example, this code renders “Hello, Sarah” on the page :
What happens in this example:
- We call ReactDOM.render() with the <Welcome name="Sarah" />element.
- React calls the Welcome component with {name: 'Sarah'} as the props.
- Our Welcome component returns a <h1>Hello, Sarah</h1> element as the result.
- React DOM efficiently updates the DOM to match <h1>Hello, Sarah</h1>.
Note: Always start component names with a capital letter.
Composing Components
Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.
For example, we can create an App component that renders Welcomemany times:
Props are Read-Only
Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum function :
Such functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs.
In contrast, this function is impure because it changes its own input :