1. Basics of React Components
What are Components?
- Components are the building blocks of React applications.
- They allow you to split the UI into independent, reusable pieces.
- Components can be functional or class-based.
Functional Components
- Definition: These are JavaScript functions that accept props and return React elements.
- When to Use: Prefer functional components because they are simpler and support hooks.
import React from 'react';
const Greeting = () => {
return <h1>Hello, World!</h1>;
};
export default Greeting;
Explanation:
- The
Greeting
component is a function that returns a React element (<h1>
). - React renders this as a piece of the UI.
- This component has no state or side effects, making it a “stateless” component.
Props Example:
const Welcome = (props) => {
return <h1>Welcome, {props.name}!</h1>;
};
// Usage
<Welcome name="Erik" />
Key Points:
- Functional components are stateless unless using hooks.
- They can receive props and display dynamic data.
Class Components
- Definition: Class components are ES6 classes extending
React.Component
. - When to Use: Use only if you need lifecycle methods or state without hooks.
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Welcome, {this.props.name}!</h1>;
}
}
export default Welcome;
Explanation:
Welcome
is a class component inheriting fromReact.Component
.- It uses
render()
method to return JSX. this.props
is used to access props in class components.
State in Class Components:
class Counter extends Component {
constructor() {
super();
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
Key Points:
- Class components manage state with
this.state
. - Use
this.setState()
to update state. - Event handlers need to be bound to the component’s context (
this
).
2. Props and State
Props
- Definition: Props (short for properties) are read-only data passed from parent to child.
- Purpose: To pass data and configuration to child components.
const User = ({ name, age }) => {
return <p>{name} is {age} years old.</p>;
};
// Usage
<User name="Alice" age={25} />
Explanation:
- Props are immutable, ensuring components remain pure and reusable.
- In functional components, props are received as a parameter.
Default Props and PropTypes (Type Checking):
User.defaultProps = {
age: 18,
};
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
};
State (Using Hooks)
- Definition: State is mutable data managed within the component.
- Purpose: To control component behavior and re-render UI on state changes.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Explanation:
useState()
is a React Hook for adding state to functional components.- It returns a state variable (
count
) and a state updater function (setCount
). - The component re-renders whenever the state changes.
Key Points:
- State is local to the component.
useState
can take a function to initialize state based on props or calculations.
3. Component Communication
Parent to Child (Using Props)
- Definition: Data is passed down from parent to child using props.
const Parent = () => {
const message = "Hello from Parent!";
return <Child text={message} />;
};
const Child = ({ text }) => <p>{text}</p>;
Explanation:
- The
Parent
component passesmessage
as a prop toChild
. - The
Child
component receivestext
as a prop and displays it.
Child to Parent (Using Callbacks)
- Definition: Child components communicate with parents using callbacks.
const Parent = () => {
const handleData = (data) => {
console.log('Data from child:', data);
};
return <Child sendData={handleData} />;
};
const Child = ({ sendData }) => {
return (
<button onClick={() => sendData('Hello Parent!')}>Send Data</button>
);
};
Explanation:
Parent
passes a function (handleData
) toChild
as a prop (sendData
).Child
callssendData
when the button is clicked, sending data to the parent.
Sibling Communication (State Lifting)
- Definition: Siblings communicate by lifting state to their common parent.
- Approach:
- Move shared state to the parent component.
- Pass state and updater functions as props to siblings.
const Parent = () => {
const [value, setValue] = useState('');
return (
<>
<ChildA value={value} onChange={setValue} />
<ChildB value={value} />
</>
);
};
const ChildA = ({ value, onChange }) => (
<input value={value} onChange={(e) => onChange(e.target.value)} />
);
const ChildB = ({ value }) => <p>Input: {value}</p>;
Explanation:
Parent
manages the state (value
) and passes it to bothChildA
andChildB
.ChildA
updates the state, which re-renders both components.