React Components

In React, a component is a modular and reusable piece of code that encapsulates a specific piece of functionality and can be composed together to create more complex user interfaces. Components can be thought of as building blocks of a React application.

There are two main types of React components: functional components and class components.

Functional components are simply functions that return a JSX element. Here’s an example:

				
					import React from 'react';

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

export default Greeting;

				
			

In this example, we’re defining a functional component called Greeting that takes a name prop and uses it to render a personalized greeting.

Class components are more powerful and offer additional features such as state and lifecycle methods. Here’s an example:

				
					import React, { Component } from 'react';

class Counter extends Component {
  state = {
    count: 0
  };

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

export default Counter;

				
			

In this example, we’re defining a class component called Counter that maintains a count in its state and renders a button that increments the count when clicked.

Components can also be composed together to create more complex user interfaces. Here’s an example that shows how to use the Greeting and Counter components together:

				
					import React from 'react';
import Greeting from './Greeting';
import Counter from './Counter';

function App() {
  return (
    <div>
      <Greeting name="Alice" />
      <Counter />
    </div>
  );
}

export default App;

				
			

In this example, we’re defining an App component that renders a Greeting component with a name prop and a Counter component. The result is a user interface that displays a personalized greeting and a counter that can be incremented by the user.

Overall, React components provide a powerful way to organize and reuse code in a React application, making it easier to build and maintain complex user interfaces.

Join To Get Our Newsletter
Spread the love