Sobes.tech
Junior

Räägi mulle Reacti komponentidest.

sobes.tech AI

Vastus AI-lt

In React, components are independent, reusable elements of the user interface that can accept input data (props) and manage their own state.

There are two main types of components:

  1. Functional components: Simple JavaScript functions that return JSX.

    // Example of a functional component
    function Welcome(props) {
      return <h1>Hello, {props.name}!</h1>;
    }
    
  2. Class components: JavaScript classes that extend React.Component and have a render() method that returns JSX. They can have local state (state) and lifecycle methods.

    // Example of a class component
    class Counter extends React.Component {
      constructor(props) {
        super(props);
        this.state = { count: 0 };
      }
    
      render() {
        return (
          <div>
            <p>Counter: {this.state.count}</p>
            <button onClick={() => this.setState({ count: this.state.count + 1 })}>
              Increment
            </button>
          </div>
        );
      }
    }
    

Components can be nested within each other to create more complex interfaces. Data is passed from parent component to child component via props.

Using components ensures modularity, code reuse, and simplifies state management of the application.