Índice De Conteúdo
Introduction to React.js
React.js is a popular JavaScript library for building user interfaces, especially single-page applications. Developed by Facebook, React makes it easy to build interactive UIs with its component-based structure and powerful features like the virtual DOM, hooks, and efficient state management. This guide will introduce you to the basics of React, providing a solid foundation for building dynamic, responsive web applications.
Table of Contents
- What is React.js?
- Setting Up a React Environment
- Introduction to JSX
- React Components
- Props in React
- State in React
- Handling Events in React
- Using Hooks in React
- React Router for Navigation
- Basic Styling in React
- Building a Simple React Application
- Conclusion: Getting Started with React.js
1. What is React.js?
React.js is a JavaScript library used to create fast, scalable, and simple user interfaces. It’s widely known for its component-based architecture and virtual DOM features, which make developing complex web applications more efficient.
Key Features of React
- Component-Based Architecture: Break down UIs into reusable components.
- Virtual DOM: Enables fast and efficient updating of UI elements.
- Declarative: Describe what the UI should look like at any point, and React will handle the updates.
React is often used for building single-page applications (SPAs) where the page dynamically updates as the user interacts with it, without the need for a full-page reload.
2. Setting Up a React Environment
Before building with React, you’ll need to set up your environment.
Install Node.js and npm
React requires Node.js and npm to manage packages and dependencies.
- Download Node.js from nodejs.org and install it.
- Verify installation by running:
node -v
npm -v
Create a React Project with Create React App
Create React App is a tool that sets up a new React project with all the necessary configurations.
npx create-react-app my-app
cd my-app
npm start
After running npm start
, your application will be available at http://localhost:3000
.
3. Introduction to JSX
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML directly within JavaScript code. JSX makes React code more readable and easier to write, especially for building UIs.
Example of JSX:
const element = <h1>Hello, World!</h1>;
While it looks like HTML, JSX is transpiled into JavaScript using tools like Babel. For example, <h1>Hello, World!</h1>
is converted into React.createElement('h1', null, 'Hello, World!')
during build time.
Embedding Expressions
JSX allows you to embed JavaScript expressions directly within your HTML-like syntax.
const name = 'Alice';
const element = <h1>Hello, {name}!</h1>;
4. React Components
Components are the building blocks of React applications. A component is a self-contained piece of code that controls a section of the UI.
Types of Components
- Functional Components: Functions that return JSX. With the addition of hooks, functional components are now powerful and commonly used.
function Welcome() {
return <h1>Hello, World!</h1>;
}
- Class Components: ES6 classes that extend
React.Component
. These were historically used for managing state and lifecycle methods but are less common since the introduction of hooks.
class Welcome extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
Components allow you to break down complex UIs into smaller, reusable parts, making applications more modular and easier to maintain.
5. Props in React
Props (short for properties) allow data to be passed from a parent component to a child component. Props are immutable, meaning they cannot be changed by the receiving component.
Example of passing props:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage in a parent component
<Welcome name="Alice" />
Props make components more flexible and reusable by allowing data to be customized for different instances.
6. State in React
State is an object that holds dynamic data in a component. Unlike props, state is mutable and can change over time, making it ideal for managing data that needs to be interactive.
Using State in Functional Components with useState
The useState
hook allows functional components to manage state.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example, count
is the state variable, and setCount
is the function used to update it.
7. Handling Events in React
React uses synthetic events to handle user interactions, providing a cross-browser wrapper around the native DOM events.
Example of handling a click event:
function Button() {
const handleClick = () => alert('Button was clicked!');
return <button onClick={handleClick}>Click Me</button>;
}
React events are similar to standard DOM events, but event names use camelCase, such as onClick
instead of onclick
.
8. Using Hooks in React
Hooks were introduced in React 16.8, allowing you to manage state and lifecycle methods in functional components. Some of the most common hooks include:
- useState: Manages state in a functional component.
- useEffect: Handles side effects, like data fetching or updating the DOM.
- useContext: Shares data between components without prop drilling.
Example of useEffect
:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => setData(json));
}, []);
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
useEffect
runs after the component renders, making it ideal for data fetching and other side effects.
React Router is a popular library for managing navigation and creating single-page applications with multiple views.
Setting Up React Router
- Install React Router:
npm install react-router-dom
- Configure Routes:
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
React Router makes it easy to add navigation and handle URL changes within a React application.
10. Basic Styling in React
React supports multiple ways to style components, including:
- CSS Stylesheets: Link an external CSS file and apply styles using
className
. - Inline Styles: Use inline styles in JSX, written as objects.
- CSS Modules: Scope styles locally to each component.
- Styled Components: Use CSS-in-JS libraries to write CSS directly within JavaScript files.
Example with CSS Modules:
/* Button.module.css */
.button {
background-color: blue;
color: white;
}
import styles from './Button.module.css';
function Button() {
return <button className={styles.button}>Styled Button</button>;
}
Each styling method offers different advantages, depending on the project’s requirements.
11. Building a Simple React Application
Now that we’ve covered the basics, let’s build a simple application—a to-do list.
To-Do List Component
import React, { useState } from 'react';
function TodoApp() {
const [tasks, setTasks] = useState([]);
const [input, setInput] = useState('');
const addTask = () => {
setTasks([...tasks, input]);
setInput('');
};
return (
<div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="New task"
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((task, index) => (
<li key={index}>{task}</li>
))}
</ul>
</div>
);
}
export default TodoApp;
In this example, we use useState
to manage the task list and input state. Each task added by the user is displayed in an unordered list.
12. Conclusion: Getting Started with React.js
React.js provides a powerful set of tools for building interactive U
Is. With a solid understanding of components, props, state, hooks, and events, you’re well-equipped to create dynamic applications. As you gain experience, you can expand your React knowledge with advanced concepts like context, lifecycle methods, and third-party libraries for state management and routing. React’s flexibility and ease of use make it an excellent choice for modern web development, enabling developers to build responsive and efficient applications.