React components are the building blocks of any React application. A component is a self-contained module that renders some output. It can have its own state and props.
They are simpler, stateless components, used for presentational purposes. Functional components have improved with the introduction of Hooks in React v16.8, allowing them to use state and other features.
Before Hooks, class components were the only way to use state and lifecycle methods in a React application. They are more complex compared to functional components but are still used widely.
Here’s a functional component example:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
And, a class component example:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Props (properties) are immutable pieces of data that are passed from the parent component.
In a functional component, props are accessed like this:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
In a class component, props can be accessed via `this.props`:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
State allows components to create and manage their own data. It's only available in class components and functional components that use the `useState` hook.
In a class component:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: 0};
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
In a functional component using the `useState` hook:
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
Lifecycle methods are hooks that allow execution of code at different points in a component's life. In class components, they include methods like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`.
In a class component:
class App extends React.Component {
componentDidMount() {
console.log('Component Did Mount');
}
componentDidUpdate() {
console.log('Component Did Update');
}
componentWillUnmount() {
console.log('Component Will Unmount');
}
render() {
return <div>Hello World</div>;
}
}
In functional components, lifecycle methods can be replicated using the `useEffect` hook:
function App() {
React.useEffect(() => {
console.log('Equivalent to componentDidMount');
return () => {
console.log('Equivalent to componentWillUnmount');
};
}, []);
React.useEffect(() => {
console.log('Equivalent to componentDidUpdate');
});
return <div>Hello World</div>;
}
Event handling in React components is straightforward and can be done inline or by referencing a function.
In a class component:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
In a functional component:
function Toggle() {
const [isToggleOn, setToggle] = React.useState(true);
const handleClick = () => {
setToggle(!isToggleOn);
};
return (
<button onClick={handleClick}>
{isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
React allows components to render different UIs based on conditions, using conditional (ternary) operators, logical && operator, or if-else blocks.
function Welcome(props) {
return (
<div>
{props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
</div>
);
}
When rendering a list, each list item needs a unique `key` prop, which helps React identify which items have changed, are added, or are removed.
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<li key={number.toString()}>{number}</li>
);
return <ul>{listItems}</ul>;
}
React components can also control form inputs through techniques known as "Controlled Components."
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
The Context API allows passing data through the component tree without having to pass props down manually at every level.
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return <button theme={this.context}>Themed Button</button>;
}
}
React components, whether functional or class-based, are the essence of React applications, offering a modular and maintainable approach to building user interfaces. The examples provided above serve as basic illustrations to understand various aspects of React components like state, props, lifecycle methods, event handling, conditional rendering, lists and keys, forms, and the Context API. Further exploration and practice with these concepts will aid in developing proficiency in creating React applications.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here