
Hola Hivers, espero que todos esten contentos y felices. Un saludos especial a la comunidad y a los desarrolladores!
> ENGLISH VERSION AT THE END.
### Serie de Tutoriales de React, Hive y Typescript
Tratando de modernizar lo que se encuentra actualmente disponible, me atrevo a compartir el conocimiento para que otros desarrolladores de React y Web3 puedan aprender y profundizar. Estare entregando tutoriales modernos usando herramientas como:
- ReactJS, Typescript, Vite, Webpack, Nodejs, Dhive, Hive Keychain, keychain-helper y todo lo que haga falta.
----
> Muy importante: debes estar familiarizado con crear proyectos usando comandos de terminal, npm o yarn u otro manejador de paquetes. Y debes tener instalado en tu sistema operativo [nodejs](https://nodejs.org/en). Y un editor de codigo. Recomiendo [VSCode](https://code.visualstudio.com/).
----
### He dispuesto el proyecto matriz [Aca](https://github.com/theghost1980/react-hive-tutorials)
Lo puedes clonar o descargar y correr en tu PC.
1. Copia el enlace `https://github.com/theghost1980/react-hive-tutorials.git`.

2. Ve a tu editor de codigo, ejemplo: VSCode y busca la opcion "Source Control" y elige "Clonar repositorio".
3. Una vez clonado, y dentro de la carpeta raiz, simplemente ejecuta:
`npm install` o si usas yarn: `yarn add`
4. Y corres la aplicación:
```
npm run dev
```
o usando yarn:
```
yarn dev
```
### Que encontraras en dicho [proyecto](https://github.com/theghost1980/react-hive-tutorials/blob/main/README.md)?
Un indice con el codigo completado de cada entrega.
> La idea es que vayas haciendo el codigo con la ayuda de este post y luego puedas comparar o revisar para corregir de ser necesario.
----
### Código base del lector de publicaciones Tutorial #1
- Dentro de tu editor de código, crea un nueva carpeta e inicializa usando:
`npm init -y` esto creara un archivo package.json con informacion por defecto.
- Ahora instalemos todo lo que necesitamos:
```
npm install react react-dom axios
```
- Seguimos instalando:
```
npm install --save-dev typescript @types/react @types/react-dom vite
```
- Crea el archivo `vite.config.ts` en tu directorio raiz y su contenido debe ser:
```
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
});
```
- En el mismo directorio raiz, creamos el archivo `tsconfig.json` con:
```
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"jsx": "react-jsx",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
```
> Ojo no me detengo en lo basico sobre configuraciones ya que siempre puedes hablar con chatgpt o gemini y con gusto te daran mucha guia :)
- Ahora creeemos en raiz, la carpeta `src`, ya que es una practica estandar para ubicar los archivos de codigo fuente.
- Dentro de la recien creada carpeta `src`, creamos el archivo
`main.tsx`, y su contenido debe ser:
```
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
```
- Y ahora debemos crear `App.tsx` con:
```
import React, { useEffect, useState } from "react";
import axios from "axios";
interface Post {
title: string;
author: string;
permlink: string;
created: string;
}
export default function App() {
const [posts, setPosts] = useState<Post[]>([]);
useEffect(() => {
const fetchPosts = async () => {
const response = await axios.post("https://api.hive.blog", {
jsonrpc: "2.0",
method: "condenser_api.get_discussions_by_created",
params: [{ tag: "hive", limit: 5 }],
id: 1,
});
setPosts(response.data.result);
};
fetchPosts();
}, []);
return (
<div style={{ padding: "2rem" }}>
<h1>📝 Publicaciones recientes en Hive</h1>
<ul>
{posts.map((post) => (
<li key={post.permlink}>
<a
href={`https://peakd.com/@${post.author}/${post.permlink}`}
target="_blank"
rel="noopener noreferrer"
>
{post.title}
</a>{" "}
<small>por @{post.author}</small>
</li>
))}
</ul>
</div>
);
}
```
- Por ultimo debemos agregar nuestro archivo `index.html`, con el contenido:
```
<!-- tutorials/01-hive-post-reader/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Tutorial 01 - Hive Reader</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
```
-> Ahora ya podemos correr nuestra primera app de Hive & React, haciendo:
`npx vite` dentro de la terminal de VSCode. Y deberiamos ver esto en la terminal:

Y podemos hacer `CTRL + Clic` sobre el enlace y se abre automaticamente el navegador con la App corriendo. Y deberias ver:


<sup>[fuente](https://imgflip.com/memegenerator/Leonardo-Dicaprio-Cheers)</sup>
----
### 🧠 Un poco de conceptos básicos
- **Vite** se encarga de ser el _bundler_ o empaquetador moderno que sirve tu aplicación durante el desarrollo y la compila para producción. Es rápido, ligero y reemplaza a herramientas como Webpack. → [vitejs.dev](https://vitejs.dev)
- **React** es quien se encarga de construir interfaces de usuario declarativas usando componentes reutilizables. Es la biblioteca principal que usamos para renderizar la UI. → [reactjs.org](https://reactjs.org)
- **TypeScript** es quien agrega tipado estático sobre JavaScript. Esto ayuda a detectar errores antes de tiempo y mejorar el autocompletado en el código. → [typescriptlang.org](https://www.typescriptlang.org)
- **Axios** es quien facilita hacer peticiones HTTP desde JavaScript o TypeScript. Lo usamos para conectarnos fácilmente a la API de Hive usando `POST`. → [axios-http.com](https://axios-http.com)
- **JSON-RPC** es el mecanismo o protocolo encargado de enviar comandos a la blockchain de Hive (como leer posts) mediante llamadas HTTP. Es simple y basado en JSON. → [json-rpc.org](https://www.jsonrpc.org/specification)
- La **página `index.html`** sirve como punto de entrada principal para la aplicación. Es el archivo que Vite carga y dentro del cual React renderiza todo.
- **npm** es quien gestiona las dependencias del proyecto. Permite instalar librerías como React, axios o Vite, y ejecutar scripts del proyecto. → [npmjs.com](https://www.npmjs.com)
----
### Datos interesantes para el desarrollador:
> Sabías que Hive Keychain, aunque es una extension para Navegadores en esencia es una aplicación hecha en React y Typescript?
> En cambio tribaldex.com esta desarrollada en Vue que es otro marco de trabajo para aplicaciones web modernas.
-----
## 🚀 ¿Querés ir un paso más allá?
Te dejo un desafío opcional para aplicar lo que aprendiste:
> 🧪 **Permitir al usuario elegir la etiqueta (`tag`) que quiere consultar.**
En lugar de traer siempre publicaciones de la etiqueta `hive`, podés agregar un campo de texto y que el usuario escriba la que quiera (por ejemplo: `spanish`, `photography`, `programacion`, etc.). Luego hacé que se actualicen los resultados según esa entrada.
---
### 💡 Otros retos que podés intentar:
- Mostrar la fecha del post de forma legible (ej: `1 de mayo, 2025`)
- Agregar un botón "Refrescar" para recargar los datos
- Mostrar número de votos o payout estimado
- Filtrar por autor
- Limitar la cantidad de resultados mostrados
---
> Seguiremos conectados para traerles la proxima entrega! Y Si quieren algun tutorial especifico pues deja en comentarios.
<details>
<summary>English Version Here</summary>
Hi Hivers, I hope everyone is happy and happy. Special greetings to the community and developers!
### React, Hive and Typescript Tutorial Series
Trying to modernize what is currently available, I dare to share the knowledge so that other React and Web3 developers can learn and go deeper. I will be delivering modern tutorials using tools like:
- ReactJS, Typescript, Vite, Webpack, Nodejs, Dhive, Hive Keychain, keychain-helper and everything you need.
----
> Very important: You should be familiar with creating projects using terminal, npm or yarn commands or another package handler. And you must have [nodejs](https://nodejs.org/en). and a code editor installed on your operating system. I recommend [VSCode](https://code.visualstudio.com/).
----
### I have arranged the parent project [Here](https://github.com/theghost1980/react-hive-tutorials)
You can clone it or download and run it on your PC.
1. Copy the link `https://github.com/theghost1980/react-hive-tutorials.git`.

2. Go to your code editor, example: VSCode and look for the "Source Control" option and choose "Clone repository".
3. Once cloned, and inside the root folder, simply run:
`npm install` or if you use yarn:`yarn add`
4. And you run the application:
```
npm run dev
```
or using yarn:
```
yarn dev
```
### What you will find in this [project](https://github.com/theghost1980/react-hive-tutorials/blob/main/README.md)?
An index with the completed code of each delivery.
> The idea is that you make the code with the help of this post and then you can compare or review to correct if necessary.
----
### Post Reader Base Code Tutorial #1
- Inside your code editor, create a new folder and initialize using:
`npm init -and` this will create a package.json file with default information.
- Now let's install everything we need:
```
npm install react react-dom axios
```
- We continue installing:
```
npm install --save-dev typescript @types/react @types/react-dom vite
```
- Create the file `vite.config.ts` in your root directory and its contents should be:
```
import { definesConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default definesConfig({
plugins: [react()],
});
```
- In the same root directory, we create the file `tsconfig.json` with:
```
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"jsx": "react-jsx",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
```
> Be careful, I don't dwell on the basics about configurations since you can always talk to chatgpt or gemini and they will gladly give you a lot of guidance:)
- Now we believe in root, the `src` folder, since it is standard practice to locate source code files.
- Inside the newly created `src` folder, we create the file
`main.tsx`, and its content must be:
```
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
```
- And now we must create `App.tsx` with:
```
import React, {useEffect, useState } from "react";
import axios from "axios";
post interface {
title: string;
author: string;
permlink: string;
created: string;
}
export default function App() {
const [posts, setPosts] = useState<Post[]>([]);
useEffect(() => {
const fetchPosts = async() => {
const response = await axios.post("https://api.hive.blog", {
jsonrpc: "2.0",
method: "condenser_api.get_discussions_by_created",
params: [{ tag: "hive", limit: 5 }],
id: 1,
});
setPosts(response.data.result);
};
fetchPosts();
}, []);
return (
<div style={{ padding: "2rem" }}>
<h1>📝 Recent posts on Hive</h1>
<ul>
{posts.map((post) => (
<li key={post.permlink}>
<a
href={`https://peakd.com/@${post.author}/${post.permlink}`}
target="_blank"
rel="noopener noreferrer"
>
{post.title}
</a>{" "}
<small>by @{post.author}</small>
</li>
))}
</ul>
</div>
);
}
```
- Finally we must add our `index.html` file, with the content:
```
<!-- tutorials/01-hive-post-reader/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Tutorial 01 - Hive Reader</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
```
-> Now we can run our first Hive & React app, doing:
`npx vite` inside the VSCode terminal. And we should see this in the terminal:

And we can do `CTRL + Click on the link and the browser automatically opens with the App running. And you should see:


<sup>[source](https://imgflip.com/memegenerator/Leonardo-Dicaprio-Cheers)</sup>
----
### 🧠 A little basics
- **Vite** is responsible for being the modern _bundler_ or packager that serves your application during development and compiles it for production. It's fast, lightweight, and replaces tools like Webpack. → [vitejs.dev](https://vitejs.dev)
- **React** is responsible for building declarative user interfaces using reusable components. It is the main library that we use to render the UI. → [reactjs.org](https://reactjs.org)
- **TypeScript** is the one who adds static typing over JavaScript. This helps detect errors early and improve autocomplete in the code. → [typescriptlang.org](https://www.typescriptlang.org)
- **Axios** is the one who makes it easy to make HTTP requests from JavaScript or TypeScript. We use it to easily connect to the Hive API using `POST`. → [axios-http.com](https://axios-http.com)
- **JSON-RPC** is the mechanism or protocol responsible for sending commands to the Hive blockchain (such as reading posts) using HTTP calls. It is simple and based on JSON. → [json-rpc.org](https://www.jsonrpc.org/specification)
- The **page `index.html`** serves as the primary entry point for the application. It is the file that Vite loads and within which React renders everything.
- **npm** is the one who manages the project dependencies. Allows you to install libraries such as React, axios or Vite, and run project scripts. → [npmjs.com](https://www.npmjs.com)
----
### Interesting facts for the developer:
> Did you know that Hive Keychain, although it is an extension for Browsers, is it essentially an application made in React and Typescript?
> On the other hand, tribaldex.com is developed in Vue, which is another framework for modern web applications.
-----
## 🚀 Do you want to go one step further?
I leave you an optional challenge to apply what you learned:
> 🧪 **Allow the user to choose the tag (`tag`) they want to consult.**
Instead of always bringing posts from the `hive` tag, you can add a text field and have the user type whatever they want (for example: `spanish`, `photography`, `programming`, etc.). Then have the results updated based on that entry.
---
### 💡 Other challenges you can try:
- Show the date of the post legibly (e.g. `May 1, 2025`)
- Add a "Refresh" button to reload the data
- Show number of votes or estimated payout
- Filter by author
- Limit the number of results displayed
---
> We will remain connected to bring you the next delivery! And if you want a specific tutorial, leave it in the comments.
</details>