Junior
Tell about the components in React.
sobes.tech AI
Answer from AI
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:
-
Functional components: Simple JavaScript functions that return JSX.
// Example of a functional component function Welcome(props) { return <h1>Hello, {props.name}!</h1>; } -
Class components: JavaScript classes that extend
React.Componentand have arender()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 to child components via props.
Using components ensures modularity, code reusability, and simplifies application state management.