What is a Component?
A component is a JavaScript function or class that optionally accepts inputs (called “props”) and returns a React element describing what should appear on the screen.Function Components
The simplest way to define a component is to write a JavaScript function:- Accept a single
propsobject argument with data - Return a React element
- Can use Hooks to add state and lifecycle features
Class Components
You can also define components using ES6 classes. Class components extend fromReact.Component or React.PureComponent.
- Component
- PureComponent
Component base class provides:this.props- The props passed to the componentthis.context- The context value (if using context)this.refs- An object for accessing refsthis.setState(partialState, callback)- Updates component statethis.forceUpdate(callback)- Forces a re-render
Modern React Development: While class components are still fully supported, the React team recommends using function components with Hooks for new code. Function components are simpler, require less code, and work better with modern React features.
Component Composition
Components can contain other components, allowing you to build complex UIs from simple building blocks:Props Children
Components can pass children to other components using the specialprops.children property:
props.children:
React.Children.map(children, fn)- Invokes a function on every immediate childReact.Children.forEach(children, fn)- Like map but doesn’t return an arrayReact.Children.count(children)- Returns the total number of childrenReact.Children.only(children)- Verifies that children has only one child and returns itReact.Children.toArray(children)- Returns the children as a flat array with keys
Component Names
Always start component names with a capital letter:<Welcome />- React treats this as a component<welcome />- React treats this as a DOM tag (like<div>or<span>)
Props are Read-Only
Whether you declare a component as a function or a class, it must never modify its own props:Pure Functions: All React components must act like pure functions with respect to their props. This means that given the same inputs (props), a component should always return the same output.
Next Steps
JSX
Learn about JSX syntax and how it transforms to JavaScript
Props and State
Understand how to pass data and manage component state