{"id":1675,"date":"2024-08-02T11:04:17","date_gmt":"2024-08-02T09:04:17","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1675"},"modified":"2024-08-02T11:04:18","modified_gmt":"2024-08-02T09:04:18","slug":"008-enrutamiento-router","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/18-single-page-application-spa\/008-enrutamiento-router\/","title":{"rendered":"008. Enrutamiento (Router)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">En el cap\u00edtulo anterior aprendimos a pintar en pantalla lo que eran las \u00faltimas 10 publicaciones de nuestro sitio <strong>WordPress<\/strong> a trav\u00e9s de la API del mismo.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">En este cap\u00edtulo construimos un <strong>router<\/strong> en el que dependiendo de la secci\u00f3n en la que nos encontremos, pueda generar el contenido correspondiente. Crearemos un <strong>componente<\/strong> nuevo denominado <em>Router.js<\/em>. En este archivo es donde vamos a tener toda la invocaci\u00f3n de las peticiones que tenemos que hacer dependiendo la secci\u00f3n de contenido que necesitemos.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p class=\"wp-block-paragraph\">En este cap\u00edtulo hemos creado el archivo <em>Router.js<\/em> y modificado los archivos <em>index.js<\/em>, <em>ajax.js<\/em>, <em>Menu.js<\/em> <em>App.js<\/em>. La sintaxis para cada uno de los archivos es.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sintaxis de <em>Router.js<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import api from \"..\/helpers\/wp-api.js\";\nimport { ajax } from \"..\/helpers\/ajax.js\";\nimport { PostCard } from \".\/PostCard.js\";\n\nexport function Router() {\n&nbsp; const d = document,\n&nbsp; &nbsp; w = window,\n&nbsp; &nbsp; $posts = d.getElementById(\"posts\");\n\n&nbsp; let { hash } = location;\n&nbsp; console.log(hash);\n\n&nbsp; $posts.innerHTML = null;\n\n&nbsp; if (!hash || hash === \"#\/\") {\n&nbsp; &nbsp; ajax({\n&nbsp; &nbsp; &nbsp; url: api.POSTS,\n&nbsp; &nbsp; &nbsp; cbSuccess: (posts) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/console.log(posts);\n&nbsp; &nbsp; &nbsp; &nbsp; let html = \"\";\n&nbsp; &nbsp; &nbsp; &nbsp; posts.forEach((post) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; html += PostCard(post);\n&nbsp; &nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &nbsp; &nbsp; d.querySelector(\".loader\").style.display = \"none\";\n&nbsp; &nbsp; &nbsp; &nbsp; $posts.innerHTML = html;\n&nbsp; &nbsp; &nbsp; },\n&nbsp; &nbsp; });\n&nbsp; } else if (hash.includes(\"#\/search\")) {\n&nbsp; &nbsp; $posts.innerHTML = `&lt;h2&gt;Secci\u00f3n del Buscador&lt;\/h2&gt;`;\n&nbsp; } else if (hash === \"#\/contacto\") {\n&nbsp; &nbsp; $posts.innerHTML = `&lt;h2&gt;Secci\u00f3n de Contacto&lt;\/h2&gt;`;\n&nbsp; } else {\n&nbsp; &nbsp; $posts.innerHTML = `&lt;h2&gt;Aqu\u00ed se carga el contenido del post seleccionado&lt;\/h2&gt;`;\n&nbsp; }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Sintaxis de <em>App.js<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import { Header } from \".\/components\/Header.js\";\nimport { Loader } from \".\/components\/Loader.js\";\nimport { Posts } from \".\/components\/Posts.js\";\nimport { Router } from \".\/components\/Router.js\";\n\nexport function App() {\n&nbsp; const $root = document.getElementById(\"root\");\n&nbsp; $root.appendChild(Header());\n&nbsp; $root.appendChild(Posts());\n&nbsp; $root.appendChild(Loader());\n&nbsp; Router();\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Sintaxis de <em>index.js<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import { App } from \".\/App.js\";\n\ndocument.addEventListener(\"DOMContentLoaded\", App);\n\nwindow.addEventListener(\"hashchange\", App);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Sintaxis de <em>ajax.js<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">export function ajax(props) {\n&nbsp; let { url, cbSuccess } = props;\n\n&nbsp; fetch(url)\n&nbsp; &nbsp; .then((res) =&gt; (res.ok ? res.json() : Promise.reject(res)))\n&nbsp; &nbsp; .then((json) =&gt; cbSuccess(json))\n&nbsp; &nbsp; .catch((err) =&gt; {\n&nbsp; &nbsp; &nbsp; let message = err.statusText || \"Ocurri\u00f3 un error al acceder a la API\";\n&nbsp; &nbsp; &nbsp; document.getElementById(\"posts\").innerHTML = `\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;div class=\"error\"&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;p&gt;Error: ${err.status}: ${message}&lt;\/p&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;\/div&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; `;\n&nbsp; &nbsp; &nbsp; document.querySelector(\".loader\").style.display = \"none\";\n&nbsp; &nbsp; &nbsp; console.log(err);\n&nbsp; &nbsp; });\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Sintaxis de <em>Menu.js<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">export function Menu() {\n&nbsp; const $menu = document.createElement(\"nav\");\n&nbsp; $menu.classList.add(\"menu\");\n&nbsp; $menu.innerHTML = `\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;a href=\"#\/\"&gt;Home&lt;\/a&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;span&gt;&lt;\/span&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;a href=\"#\/search\"&gt;B\u00fasqueda&lt;\/a&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;span&gt;&lt;\/span&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;a href=\"#\/contacto\"&gt;Contacto&lt;\/a&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;span&gt;&lt;\/span&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;a href=\"https:\/\/sutilweb.eu\" target=\"_blank\" rel=\"noopener\"&gt;Sutil Web&lt;\/a&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;span&gt;&lt;\/span&gt;\n&nbsp; &nbsp; `;\n&nbsp; return $menu;\n}<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Archivos<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">El total de los archivos creados hasta la fecha se encuentra en el siguiente enlace:<\/p>\n\n\n\n<div class=\"wp-block-file alignleft\"><a id=\"wp-block-file--media-373c433f-2daf-4941-9d47-d2d8e1f6f9b6\" href=\"https:\/\/blog.sutilweb.eu\/wp-content\/uploads\/2024\/08\/spa-5.zip\">spa-5<\/a><a href=\"https:\/\/blog.sutilweb.eu\/wp-content\/uploads\/2024\/08\/spa-5.zip\" class=\"wp-block-file__button wp-element-button\" download aria-describedby=\"wp-block-file--media-373c433f-2daf-4941-9d47-d2d8e1f6f9b6\">Descarga<\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>En el cap\u00edtulo anterior aprendimos a pintar en pantalla lo que eran las \u00faltimas 10 publicaciones de nuestro sitio WordPress a trav\u00e9s&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1646,"menu_order":7,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","footnotes":""},"class_list":["post-1675","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"En el cap\u00edtulo anterior aprendimos a pintar en pantalla lo que eran las \u00faltimas 10 publicaciones de nuestro sitio WordPress a trav\u00e9s...","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1675","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=1675"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1675\/revisions"}],"predecessor-version":[{"id":1678,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1675\/revisions\/1678"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1646"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=1675"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}