React.js Component
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation
There are mainly two types of Components:
- Functional Component OR Stateless Component - Only props, no state
- Class Component OR Stateful Component - Both props and state.
1. Functional Component: (Stateless)
function FunctionComponent(props) { return Hello, {props.name}; } //In ES6 Style: const FunctionComponent = (props) => { return Hello, {props.name}; }
2. Class Component: (Stateful)
import React, { Component } from 'react'; class ClassComponent extends Component { render() { return (); } } export default ClassComponent;Class Component Welcome to React's - Class Component
Note:
- Always start component names with a capital letter.
-
React treats components starting with lowercase letters as DOM tags.
In JSX, if you will write component's name in lowercase, it will consider it as normal HTML tag, so developer should follow react.js guidelines.
Difference between Controlled vs Uncontrolled Component:
In controlled component, form data is handled by a React component.
In uncontrolled components, form data is handled by the DOM itself.
Features | Uncontrolled | Controlled |
---|---|---|
One time value retrieval (e.g. on submit) | ✅ | ✅ |
Validating on submit | ✅ | ✅ |
Instant field validation | ❌ | ✅ |
Conditionally disabling submit button | ❌ | ✅ |
Dynamic Inputs | ❌ | ✅ |
// In Controlled Component: // In Uncontrolled Component: // Use `inputRef.current.value` to read the current value of input.