What is a React component? What are its main elements?
Summary
In this post, we will learn in detail about components, which are the main building blocks of React.js.
Category
React.js
React interview
React component
Cover
Slug
what-is-react-component
Date
‣
author
Published
Published
React Components are the main building blocks used in the React library. They are used to create the UI (user interface) and divide the program code into modular and reusable parts. With components, different parts of an application can be managed separately, and repetitive code can be reduced.
Main Elements of React Components
Component Definition:
Functional Component: Defined as a function and created using function or an arrow function. For example:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Class Component: Defined as a class and uses the class keyword. For example:
Methods related to the component's lifecycle, used during creation, updating, and removal of components. Available in class components, for example: componentDidMount, componentDidUpdate, componentWillUnmount.
Rendering:
Specifies how the component is displayed on the screen. In class components, rendering is done through the render method, or through the return statement in functional components.
Example:
function MyComponent() {
return <div>Content here</div>;
}
JSX (JavaScript XML):
A syntax similar to HTML used in React components, which allows writing HTML-like code within JavaScript.
Example:
const element = <h1>Hello, world!</h1>;
Event Handling:
Components respond to user actions (such as button clicks). Event handlers are added through attributes like onClick, onChange.
Example:
function handleClick() {
alert('Button clicked!');
}
function Button() {
return <button onClick={handleClick}>Click Me</button>;
}
Conclusion
React components are powerful tools for creating and managing the UI. Their main elements include component definition, props and state, lifecycle methods, rendering, JSX, and event handling. These elements allow the software to be divided into modular and reusable parts.