How to create React components?
Asked by iligimul13527 days ago
36 views
Basics of components in React.
0
1 answers
1 Answer
Creating React components is a fundamental skill when building React applications. React components are the building blocks of a React UI and can be created in two main ways: **function components** and **class components**.
### Function Components
Function components are the simplest way to create components in React. They are JavaScript functions that return JSX (a syntax extension that looks like HTML) describing what the UI should look like.
Here’s an example of a simple function component:
```jsx
import React from 'react';
function Greeting() {
return Hello, welcome to React!;
}
export default Greeting;
```
Or using an arrow function:
```jsx
const Greeting = () => Hello, welcome to React!;
export default Greeting;
```
Function components are often preferred today because they are concise and, with React Hooks, can manage state and side effects.
### Class Components
Class components are ES6 classes that extend `React.Component` and must have a `render()` method returning JSX. They were the primary way to handle state and lifecycle methods before Hooks were introduced.
Example of a class component:
```jsx
import React, { Component } from 'react';
class Greeting extends Component {
render() {
return Hello, welcome to React!;
}
}
export default Greeting;
```
### Summary
- **Function components**: simpler, recommended for most use cases, can use Hooks.
- **Class components**: older style, less used now but still valid, use lifecycle methods in classes.
To use a component, import it and include it in JSX like a custom HTML tag:
```jsx
import Greeting from './Greeting';
function App() {
return (
);
}
```
This is the basics to get you started creating React components! As you advance, you’ll learn about props, state, hooks, and lifecycle methods to build dynamic and interactive UIs.
0
0
by David Park15 days ago
