Junior level: Core Concepts of React
Tags: react, webdev, javascript, programming
Published: 2024-07-01 18:43:51

## Components

### What Are Components?

Components are the building blocks of any React application. Think of components as small, reusable pieces of code that define how a section of the user interface (UI) should look and behave. Each component can manage its own state and props, making it easier to build and maintain complex UIs by breaking them down into smaller, manageable parts.

In a way, components are like Lego bricks. You can use individual bricks (components) to build larger structures (applications), making it easier to design, develop, and maintain your application.

### Functional vs. Class Components

In React, there are two main types of components: functional components and class components.

#### Functional Components

Functional components are simple JavaScript functions that accept props as an argument and return a React element. They are easy to read and write, and with the introduction of React Hooks, they have become the standard way to write components.

Example of a Functional Component:
```jsx
import React from 'react';

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

export default Greeting;
```

#### Class Components

Class components are ES6 classes that extend `React.Component` and must include a `render()` method that returns a React element. Class components were the standard way to write components before Hooks were introduced, and they are still useful for understanding the legacy code.

Example of a Class Component:
```jsx
import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

export default Greeting;
```

### Creating and Using Components

To create a component in React, define a function or class that returns a React element. You can then use this component within other components to build up your UI.

Example of Creating and Using a Functional Component:
```jsx
import React from 'react';

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

// Define the App component
function App() {
  return (
    <div>
      <Greeting name="Alice" />
      <Greeting name="Bob" />
    </div>
  );
}

export default App;
```

In this example, the `Greeting` component is used within the `App` component. The `name` prop is passed to `Greeting`, and it is displayed inside the `<h1>` tag.

## JSX (JavaScript XML)

### Introduction to JSX

JSX stands for JavaScript XML. It is a syntax extension for JavaScript that looks similar to HTML. JSX is used with React to describe what the UI should look like. Each JSX element is just syntactic sugar for calling `React.createElement(component, props, ...children)`.

JSX makes it easier to write and understand the structure of your UI components.

Example of JSX:
```jsx
const element = <h1>Hello, world!</h1>;
```

This JSX code gets compiled to:
```js
const element = React.createElement('h1', null, 'Hello, world!');
```

### Embedding Expressions in JSX

JSX allows you to embed JavaScript expressions within curly braces `{}`. This can include variables, function calls, or any valid JavaScript expression.

Example of Embedding Expressions in JSX:
```jsx
const name = 'Alice';
const element = <h1>Hello, {name}!</h1>;

const getGreeting = (name) => `Hello, ${name}!`;
const greetingElement = <h1>{getGreeting('Bob')}</h1>;
```

### JSX vs. HTML

While JSX looks similar to HTML, there are a few key differences:

1. **JSX Attributes:** In JSX, attributes are written in camelCase rather than lowercase. For example, `class` becomes `className`, and `onclick` becomes `onClick`.
   ```jsx
   <div className="container"></div>
   <button onClick={handleClick}>Click Me</button>
   ```

2. **JavaScript Expressions:** In JSX, you can embed JavaScript expressions within curly braces `{}`, which is not possible in plain HTML.
   ```jsx
   const isLoggedIn = true;
   <div>{isLoggedIn ? 'Welcome back!' : 'Please log in.'}</div>
   ```

3. **Self-Closing Tags:** JSX requires self-closing tags for elements without children, similar to XML.
   ```jsx
   <img src="image.jpg" />
   ```

4. **Fragments:** In JSX, you can use fragments to group multiple elements without adding extra nodes to the DOM.
   ```jsx
   <>
     <h1>Title</h1>
     <p>Description</p>
   </>
   ```

## Conclusion

Understanding components and JSX is fundamental to working with React. Components allow you to break down your UI into reusable, independent pieces, while JSX provides a syntax that closely resembles HTML, making it easier to describe your UI. As you continue to develop with React, mastering these core concepts will enable you to build efficient, maintainable, and scalable applications.