Language: EN

que-es-y-como-empezar-con-react

What is and how to start with React

React is a widely used JavaScript library for building user interfaces. It was developed by Facebook in 2013 and has become one of the most popular tools for modern web application development.

It allows us to build web applications in a declarative and component-based manner. This means that user interfaces are divided into independent and reusable components, each of which manages its own state and logic.

React takes care of updating and rendering only the necessary components when the application state changes. In other words, it applies reactivity (hence its name).

Some of the main features of React are:

  1. Components: React is based on components, which are independent and reusable building blocks that represent parts of the user interface.
  2. JSX: A syntax extension that allows writing HTML within JavaScript, making it easier to create user interfaces.
  3. Virtual DOM: React uses a Virtual DOM to optimize user interface updates, minimizing direct manipulations of the real DOM.
  4. Unidirectional Data Flow: Data in React flows in one direction, making it easier to track changes and debug applications.

React is Open Source, and all its code and documentation are available on the official page React.dev and the project repository on GitHub - facebook/react.

Installing React

To start using React, you first need to install Nodejs and NPM (Node Package Manager) on your computer. If you don’t know what they are, or want to learn more, here are two courses for you 👇.

Once you have these installed, you can create a new React project using Create React App, an official React tool that sets up a development environment with everything you need.

Open a terminal and run the following command to create a new React app, where my-app is the name of the application you want to give.

npx create-react-app my-app

Now go to the directory where your application has been created,

cd my-app

And we could directly start the application

npm start

Your new React application should automatically open in your browser at http://localhost:3000.

react-demo-app

That’s how easy it is! You now have the basics to start working with React.

How to use React

React is based on components, and the most basic component is the function component. Let’s see how to create and use components in a React application.

Creating a basic component

Create a file named App.js in the src directory of your project with the following content:

import React from 'react';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Welcome to my React application</h1>
      </header>
    </div>
  );
}

export default App;

JSX

In the previous example, we are using JSX, a syntax that allows writing HTML within JavaScript. Although it is not mandatory to use JSX, it makes creating user interfaces easier.

Rendering components

React renders components in the DOM using the ReactDOM.render() method. In your src/index.js file, you should have something like this:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

State and hooks

Components in React can have state (state). The state is an object that represents the internal state of the component and can change over time.

Example of using state, let’s create a stateful component using hooks, a feature of React that allows using state and other features without writing a class.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You have clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

export default Counter;

In this example,

  • We are using the useState hook to manage the state of the Counter component.
  • The initial state is 0 and setCount is the function that updates the state.

Using props

Components can receive properties (props) from the components that mount them. The properties (props) are passed to components as HTML attributes.

import React from 'react';

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

function App() {
  return (
    <div>
      <Welcome name="Alice" />
      <Welcome name="Bob" />
      <Welcome name="Charlie" />
    </div>
  );
}

export default App;

In this example

  • The Welcome component receives a name property.
  • It uses this to display a welcome message.

Applying styles to your components

React offers several ways to handle styles (CSS) in your components. Let’s take a look at some of them:

  1. CSS in separate files: The traditional way of writing CSS is still valid in React. However, it can lead to name conflicts and difficulties in maintaining the code as the application grows.

  2. Inline Styles: React allows applying styles directly to elements via the style property. While convenient for quick and simple styles, it can become less manageable for complex styles.

  3. CSS Modules: A technique to avoid CSS name conflicts by importing styles as modules.

import styles from './MyComponent.module.css';

function MyComponent() {
  return <div className={styles.myClass}>Styled content</div>;
}
  1. Styled Components: A library that allows writing CSS in your components using JavaScript.
import styled from 'styled-components';

const Box = styled.div`
  color: blue;
  font-size: 20px;
`;

function MyComponent() {
  return <Box>Styled content</Box>;
}

Managing global state

In larger applications, managing global state can be complex. React provides tools to manage this state, such as Context API and Redux.

Context API

The Context API allows passing data through the component tree without having to pass props manually at every level.

import React, { createContext, useContext, useState } from 'react';

const MyContext = createContext();

function Provider({ children }) {
  const [state, setState] = useState("initial value");

  return (
    <MyContext.Provider value={{ state, setState }}>
      {children}
    </MyContext.Provider>
  );
}

function ChildComponent() {
  const { state, setState } = useContext(MyContext);

  return (
    <div>
      <p>{state}</p>
      <button onClick={() => setState("new value")}>Change value</button>
    </div>
  );
}

function App() {
  return (
    <Provider>
      <ChildComponent />
    </Provider>
  );
}

Redux

Redux is a popular library for managing global state. It follows the principle of a single global store where all the application state is stored.

To use it, first install Redux and React-Redux:

npm install redux react-redux

Now we can start using Redux.

import { createStore } from 'redux';
import { Provider, useDispatch, useSelector } from 'react-redux';

// Action
const increment = () => ({ type: 'INCREMENT' });

// Reducer
const counter = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    default:
      return state;
  }
};

// Store
const store = createStore(counter);

function Counter() {
  const dispatch = useDispatch();
  const count = useSelector(state => state);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => dispatch(increment())}>Increment</button>
    </div>
  );
}

function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

export default App;

Deploying a React application

Once you have finished developing your application, it’s time to deploy it. You can use several deployment platforms such as Vercel, Netlify, or GitHub Pages.

Deploying on GitHub Pages

  1. Install gh-pages:
npm install gh-pages --save-dev
  1. Add the deployment scripts in package.json:
"scripts": {
  "predeploy": "npm run build",
  "deploy": "gh-pages -d build"
}
  1. Deploy your application:
npm run deploy

Download the code

All the code for this entry is available for download on GitHub. github-full