React components
Created By: chatGPT
React is a powerful JavaScript library for building user interfaces. It allows developers to create reusable components which can manage their own state. Components can be functional or class-based, providing flexibility in how you structure your application.
import React from 'react';
const MyComponent = () => {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
};
export default MyComponent;
A functional component is a simple JavaScript function that returns an element. They are typically used for presenting UI and are easier to test and debug. Let's look at how to create a functional component with props:
const Greeting = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
Class components are more powerful but more complex. They can hold and manage their own state and lifecycle methods. Here’s a basic example of a class component:
import React, { Component } from 'react';
class Timer extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.timer = setInterval(() => this.setState({ seconds: this.state.seconds + 1 }), 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return <h1>Seconds: {this.state.seconds}</h1>;
}
}
export default Timer;
Components can also manage their own state using the
useState
hook. Here’s how to do it in a functional component:import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};
React also allows you to manage side effects in functional components using the
useEffect
hook. This is useful for data fetching, subscriptions, or manually changing the DOM. Here’s an example:import React, { useState, useEffect } from 'react';
const DataFetcher = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};