Components in React
Previous articles :
Introductioon to reactjs & Basic concepts in reactjs
In React, everything revolves around components. They are the building blocks of your UI. Let’s explore some key concepts related to components:
React Components
A component in React is a reusable piece of code that encapsulates a part of the user interface. Components can be either class components or functional components.
// Example of a functional component
function MyComponent() {
return <div>Hello, World!</div>;
}
// Example of a class component
class MyComponent extends React.Component {
render() {
return <div>Hello, World!</div>;
}
}
React Class
Class components are ES6 classes that extend from React.Component
. They have a render()
method that returns the UI to be rendered.
// Example of a class component
class MyComponent extends React.Component {
render() {
return <div>Hello, World!</div>;
}
}
React Props
Props (short for properties) are a way of passing data from parent to child components. They are read-only and help make your components more dynamic and reusable.
// Example of using props in a component
function Greeting(props) {
return <div>Hello, {props.name}!</div>;
}
// Usage
<Greeting name="React" />
React Events
React allows you to handle events, such as onClick or onChange, using event handlers. These handlers are functions that are called when the event occurs.
// Example of handling click event
function handleClick() {
console.log('Button clicked!');
}
<button onClick={handleClick}>Click Me</button>
React Conditional Rendering
Conditional rendering allows you to render different components or UI elements based on certain conditions.
// Example of conditional rendering
function Greeting(props) {
if (props.isLoggedIn) {
return <UserGreeting />;
} else {
return <GuestGreeting />;
}
}
React Lists
Lists are a common feature in UI development. React makes it easy to render lists of data using the map()
function.
// Example of rendering a list
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) => <li key={number}>{number}</li>);
React Forms
Forms in React work similarly to HTML forms but with a few differences, such as using controlled components to manage form state.
// Example of a controlled component form
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
}
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>
);
}
}
Understanding these components in React will give you a solid foundation for building dynamic and interactive user interfaces.