<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: mercicodes</title>
    <description>The latest articles on Forem by mercicodes (@mercicodes).</description>
    <link>https://forem.com/mercicodes</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F850352%2F32346914-da98-4783-b87c-56f7105f2cb0.png</url>
      <title>Forem: mercicodes</title>
      <link>https://forem.com/mercicodes</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/mercicodes"/>
    <language>en</language>
    <item>
      <title>Start with Ultra, the new React web framework</title>
      <dc:creator>mercicodes</dc:creator>
      <pubDate>Mon, 25 Jul 2022 13:12:00 +0000</pubDate>
      <link>https://forem.com/mercicodes/start-with-ultra-the-new-react-web-framework-be8</link>
      <guid>https://forem.com/mercicodes/start-with-ultra-the-new-react-web-framework-be8</guid>
      <description>&lt;p&gt;&lt;a href="https://ultrajs.dev/" rel="noopener noreferrer"&gt;Ultra&lt;/a&gt; is a modern streaming React framework buily with Deno that heavily relies on the built-in functionality of your browser. It makes use of ES Modules, Import Maps, and Web Streams in the future. All the while, it supports some of the deviations from the norm that many ordinary people enjoy for whatever reason (JSX and TypeScript). Ultra uses Deno and React and focuses on using web streams and native features within the browser.&lt;/p&gt;

&lt;p&gt;Let's look at some of the reasons you should consider using Ultra for your next project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://ultrajs.dev/docs#permissions" rel="noopener noreferrer"&gt;Permissions module&lt;/a&gt;&lt;/strong&gt;: Ultra has the Deno permission-based security module features to allow you to set permissions for running your applications.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://ultrajs.dev/docs#routing" rel="noopener noreferrer"&gt;Lazy routing&lt;/a&gt;:&lt;/strong&gt; Ultra uses the Wouter a small Hooks-based router for current React and Preact projects to create routes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://ultrajs.dev/docs#suspense-data-fetching" rel="noopener noreferrer"&gt;Suspense data fetching&lt;/a&gt;&lt;/strong&gt;: Ultra uses the Vercel's &lt;a href="https://github.com/vercel/swr" rel="noopener noreferrer"&gt;SWR&lt;/a&gt; with Suspense to allow you to fetch data anywhere in your components.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://ultrajs.dev/docs#service-workers" rel="noopener noreferrer"&gt;Service Workers&lt;/a&gt;:&lt;/strong&gt; Ultra uses the vanilla Service Workers to serve, cache, and optimize your website&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://ultrajs.dev/docs#dynamic-mdx" rel="noopener noreferrer"&gt;Dynamic MDX&lt;/a&gt;&lt;/strong&gt;: Ultra has support for MDX to allow you to generate dynamic MDX in your applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Project setup
&lt;/h2&gt;

&lt;p&gt;Let's create a small book store application using Ultra.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FEvP1JrI.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FEvP1JrI.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First, we need to set up a new Ultra project by running the following commands on your terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/exhibitionist-digital/create-ultra-app
cd create-ultra-app
deno task dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command will generate the following folder structures below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;**create-ultra-app**
 ┣ src
 ┃ ┣ api
 ┃ ┃ ┗ example.ts
 ┃ ┣ app.tsx
 ┃ ┣ favicon.ico
 ┃ ┗ style.css
 ┣ .gitignore
 ┣ README.md
 ┣ deno.json
 ┣ importMap.json
 ┣ package-lock.json
 ┗ server.ts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's look at the folder structures in detail in the next section. Then start the application at &lt;a href="http://localhost:8000/" rel="noopener noreferrer"&gt;http//:localhost:8000/books&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FieopqAw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FieopqAw.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Project structure
&lt;/h2&gt;

&lt;p&gt;Ultra creates the following folder structures.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Server.ts&lt;/strong&gt;: This code runs Ultra's server.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;src&lt;/strong&gt;: This is the folder where the code for your project is.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;app.tsx&lt;/strong&gt;: This is the root file for every Ultra project.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;importMap.json:&lt;/strong&gt; Here is where dependencies for the project are documented.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;deno.json:&lt;/strong&gt; Here is where the configuration file that allows customizing the built-in TypeScript compiler, formatter, and linter.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Update app.tsx
&lt;/h2&gt;

&lt;p&gt;Let's the &lt;code&gt;app.tsx&lt;/code&gt; file to include the Bootstrap CDN to enable the style of the components. Ultra uses &lt;a href="https://github.com/staylor/react-helmet-async" rel="noopener noreferrer"&gt;react-helmet-async&lt;/a&gt; to add markup to the &lt;code&gt;html&lt;/code&gt; &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;. To replace the code in &lt;code&gt;&amp;lt;Helmet&amp;gt;&lt;/code&gt; component with the code snippet below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Helmet&amp;gt;
  &amp;lt;title&amp;gt;Book store&amp;lt;/title&amp;gt;
  &amp;lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /&amp;gt;
&amp;lt;/Helmet&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Open Source Session Replay
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblog.openreplay.com%2Fstatic%2F0a3dcbea2c3ddf66242e78ffd2a65233%2F412e4%2Fbanner-blog.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblog.openreplay.com%2Fstatic%2F0a3dcbea2c3ddf66242e78ffd2a65233%2F412e4%2Fbanner-blog.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Start enjoying your debugging experience - [start using OpenReplay for free]&lt;/em&gt;&lt;br&gt;
(&lt;a href="https://github.com/openreplay/openreplay" rel="noopener noreferrer"&gt;https://github.com/openreplay/openreplay&lt;/a&gt;).&lt;/p&gt;
&lt;h2&gt;
  
  
  Create Book Component
&lt;/h2&gt;

&lt;p&gt;Now let's create another folder called &lt;code&gt;component&lt;/code&gt; for our components. In the component folder, create a file called &lt;code&gt;Book.tsx&lt;/code&gt; and add the code snippet below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
const BookList = React.lazy(() =&amp;gt; import("./BookList.tsx"));

const books = [
  {
    id: 1,
    title: 'The Design of EveryDay Things',
    author: 'Don Norman',
    price: '$22.00',
    coverImage: 'https://miro.medium.com/max/1200/1*ixC7mJJRK55qPhyRwj3iGg.jpeg',
    description: 'Don Norman is a designer who lives and works in San Francisco. He has designed more than 100 products for companies such as Google, Motorola, and eBay. He has also designed products for non-profit organizations such as the World Food Program and UNICEF.',
  },
  {
    id: 2,
    title: 'Things fall Apart',
    author: 'Chinua Achebe',
    coverage: 'https://i0.wp.com/feminisminindia.com/wp-content/uploads/2021/07/Things_Fall_Apart_by_Chinua_Achebe_1_.jpg?fit=1200%2C675&amp;amp;ssl=1',
    description: 'Don Norman is a designer who lives and works in San Francisco. He has designed more than 100 products for companies such as Google, Motorola, and eBay. He has also designed products for non-profit organizations such as the World Food Program and UNICEF.',
  }
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we imported React and the BookList components which we'll create later in this tutorial. Then we created a book array with some book data.&lt;/p&gt;

&lt;p&gt;Now let's create and render the &lt;code&gt;JSX&lt;/code&gt; for the &lt;code&gt;Book&lt;/code&gt; component with the code snippet below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Book() {
  return (
    &amp;lt;&amp;gt;
      &amp;lt;nav class="navbar navbar-light bg-light"&amp;gt;
        &amp;lt;div class="container-fluid"&amp;gt;
          &amp;lt;a class="navbar-brand"&amp;gt;Book Store&amp;lt;/a&amp;gt;
          &amp;lt;form class="d-flex"&amp;gt;
            &amp;lt;input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" /&amp;gt;
            &amp;lt;button class="btn btn-outline-success" type="submit"&amp;gt;Search&amp;lt;/button&amp;gt;
          &amp;lt;/form&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/nav&amp;gt;
      &amp;lt;div class="container-md"&amp;gt;
        &amp;lt;div class="row"&amp;gt;
          {books.map((book) =&amp;gt; (
            &amp;lt;BookList key={book.id} book={book} /&amp;gt;
          ))}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we created the &lt;code&gt;JSX&lt;/code&gt; for the Book component and render the &lt;code&gt;BookList&lt;/code&gt; component passing the &lt;code&gt;book&lt;/code&gt; array as props.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create BookList component
&lt;/h2&gt;

&lt;p&gt;With the Book component created, let's create another component in the &lt;code&gt;component&lt;/code&gt; folder called &lt;code&gt;BookList.tsx&lt;/code&gt; file and add the code snippet below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
export default function BookList({ book }) {
    return (
        &amp;lt;div class="col-sm-6"&amp;gt;
            &amp;lt;div class="card"&amp;gt;
                &amp;lt;img src={book.coverImage} class="card-img-top" alt="..." /&amp;gt;
                &amp;lt;div class="card-body"&amp;gt;
                    &amp;lt;h5 class="card-title"&amp;gt;
                        {book.title}&amp;lt;/h5&amp;gt;
                    &amp;lt;p class="card-text"&amp;gt;{book.description}&amp;lt;/p&amp;gt;
                    &amp;lt;a href="#" class="btn btn-primary"&amp;gt;View Details&amp;lt;/a&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;

    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above snippet, we created the &lt;code&gt;BookList&lt;/code&gt; component. Here we destructure the book array from the props to access the &lt;code&gt;book&lt;/code&gt; objects and render them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding Routes
&lt;/h2&gt;

&lt;p&gt;Now let's configure a route for the application. Ultra uses a Wouter router for routing and that is already set up in the app.tsx file for you. But we need to do a few modifications. We'll render the &lt;code&gt;Book&lt;/code&gt; component on the &lt;code&gt;/books&lt;/code&gt; route.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
&amp;lt;Switch&amp;gt;
  &amp;lt;Route path="/book"&amp;gt;
    &amp;lt;Book /&amp;gt;
 &amp;lt;/Route&amp;gt;
&amp;lt;/Switch&amp;gt;
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Throughout this tutorial, you've learned about Ultra by creating a simple Book application. We started with the introduction, then we looked at some of the reasons a developer should use Ultra for their projects.&lt;br&gt;
You can learn more about Ultra from the &lt;a href="https://ultrajs.dev/docs" rel="noopener noreferrer"&gt;official documentation&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>ultra</category>
    </item>
    <item>
      <title>Building sensible UI components with React Suite</title>
      <dc:creator>mercicodes</dc:creator>
      <pubDate>Thu, 07 Jul 2022 21:59:11 +0000</pubDate>
      <link>https://forem.com/mercicodes/building-sensible-ui-components-with-react-suite-3icc</link>
      <guid>https://forem.com/mercicodes/building-sensible-ui-components-with-react-suite-3icc</guid>
      <description>&lt;h1&gt;
  
  
  How to build a sensible React Component UI using React Suite
&lt;/h1&gt;

&lt;p&gt;When building a React application, developers tend to spend most of the time writing CSS and JSX code to make the application look appealing and easy to use to the end user. In this tutorial, you'll learn how to build a sensible React Component UI using React Suite.&lt;/p&gt;

&lt;p&gt;Before we go too deep;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is React Suite
&lt;/h2&gt;

&lt;p&gt;React Suite is a set of react component libraries for enterprise system products. It is a well-thought-out and developer-friendly UI framework with supports the latest, stable releases of all major browsers and platforms. IE&amp;lt;=10 is no longer supported since React Suite 5.0. React Suite is designed and implemented for use on modern desktop browsers rather than mobile browsers.&lt;/p&gt;

&lt;h2&gt;
  
  
  What’s new in v5
&lt;/h2&gt;

&lt;p&gt;React Suite V5 has been released with lots of cool features. Let's look at some of them in a moment.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Improve accessibility&lt;/strong&gt;: All the components provided by React Suite has an improved keyboard operation and screen reading devices.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Add a set of high contrast themes&lt;/strong&gt;: React Suite has improved on the standard for color contrast requirements and has made great improvements to the components to meet most users.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use SVG Icon instead of Icon font&lt;/strong&gt;: Icon font has some rendering problems, which makes the icon blurry, the need to load the font file, and the content area flickers. For better accessibility, Version 5 prefers SVG Icon which is also well compatible with third-party icon resources.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Support CSS variables&lt;/strong&gt;:Provision has been made in version 5 to provide a set of component CSS variable configurations to make theme customization and theme switching more convenient.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Refactoring React Class Components with Hooks:&lt;/strong&gt; Most of the React Suite components have been refactored using function and adopted the new features brought by React Hooks to enhance the development experience.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Import on Demand:&lt;/strong&gt; Version 5 removes the distinction between cjs and esm when importing React Suite components&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// v4: cjs
import Button from 'rsuite/lib/Button';
// v4: esm
import Button from 'rsuite/es/Button';

// v5
import Button from 'rsuite/Button';

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What we are building
&lt;/h2&gt;

&lt;p&gt;In this tutorial, we'll be building a Photo gallery application to demonstrate how to build a sensible React component with React Suite.&lt;/p&gt;

&lt;p&gt;The project we'll be building will look like the one on the screenshot below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FyMwFYA3.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FyMwFYA3.jpg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Setup
&lt;/h2&gt;

&lt;p&gt;Let's start by setting up the new React project. Run the command below to create a React project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app react-suite-app &amp;amp;&amp;amp; cd create-react-app react-suite-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command will scaffold a new React application and change the directory into the project folder.&lt;/p&gt;

&lt;p&gt;Now open the project in your favorite text editor. For the demonstrations in this tutorial, I will be using &lt;a href="https://code.visualstudio.com/" rel="noopener noreferrer"&gt;Virtual Studio Code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Next, install the React suit module with the command below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i rsuite --save
 #or 
yarn add rsuite
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the installation is completed, let's proceed to create our components using React Suite.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create App Components
&lt;/h2&gt;

&lt;p&gt;In our App component, we'll create a navbar where the users can navigate between our components. Open the &lt;code&gt;./src/App.js&lt;/code&gt; file and update the code with the code snippets below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "rsuite/dist/rsuite.min.css";
import { Navbar, Nav, Header, Container, Content } from "rsuite";
function App() {
return (
    &amp;lt;div className="show-fake-browser navbar-page"&amp;gt;
      &amp;lt;Container&amp;gt;
        &amp;lt;Header&amp;gt;
          &amp;lt;Navbar appearance="inverse"&amp;gt;
            &amp;lt;Navbar&amp;gt;
              &amp;lt;Nav&amp;gt;
                &amp;lt;Nav.Item&amp;gt;Gallary&amp;lt;/Nav.Item&amp;gt;
                &amp;lt;Nav.Item&amp;gt;Create New&amp;lt;/Nav.Item&amp;gt;
              &amp;lt;/Nav&amp;gt;
              &amp;lt;Nav pullRight&amp;gt;
                &amp;lt;Nav.Item &amp;gt;Login&amp;lt;/Nav.Item&amp;gt;
                &amp;lt;Nav.Item&amp;gt;Signup&amp;lt;/Nav.Item&amp;gt;
              &amp;lt;/Nav&amp;gt;
            &amp;lt;/Navbar&amp;gt;
          &amp;lt;/Navbar&amp;gt;
        &amp;lt;/Header&amp;gt;
        &amp;lt;Content&amp;gt;

        &amp;lt;/Content&amp;gt;
      &amp;lt;/Container&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we imported the React Suite minified style which will apply styles to our components. We also imported the following components&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Container: Which defines the frame of our page&lt;/li&gt;
&lt;li&gt;Navbar: To add navigation to our page&lt;/li&gt;
&lt;li&gt;Nav: To add the list of the navigation menu&lt;/li&gt;
&lt;li&gt;Header: To add a header to our page&lt;/li&gt;
&lt;li&gt;Content: To define the contents of the page&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now if you open the application on your browser, you should see the output below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FUeoYfWn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FUeoYfWn.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Create Signup Form
&lt;/h2&gt;

&lt;p&gt;We need to ensure that a user is signup into the application before they can view or add their photos. To do that, we'll create a signup component to enable users to signup. To create a &lt;strong&gt;components&lt;/strong&gt; folder in the &lt;strong&gt;src&lt;/strong&gt; folder, create an &lt;code&gt;AuthModal.jsx&lt;/code&gt; file and add the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Button, Modal, Form, ButtonToolbar, Message } from "rsuite";

export const AuthModal = (props) =&amp;gt; {
  const handleClose = () =&amp;gt; props.setOpen(false);
  return (
    &amp;lt;div className="modal-container"&amp;gt;
      &amp;lt;Modal open={props.open} onClose={handleClose}&amp;gt;
        &amp;lt;Modal.Header&amp;gt;
          &amp;lt;Modal.Title&amp;gt;
            {props.isLogin ? "Login Here" : "Signup Here"}
          &amp;lt;/Modal.Title&amp;gt;
        &amp;lt;/Modal.Header&amp;gt;
        &amp;lt;Modal.Body&amp;gt;
          &amp;lt;Form fluid onSubmit={props.isLogin ? props.login : props.signUp}&amp;gt;
            &amp;lt;Form.Group controlId="email-1"&amp;gt;
              &amp;lt;Form.ControlLabel&amp;gt;Email&amp;lt;/Form.ControlLabel&amp;gt;
              &amp;lt;Form.Control
                name="email"
                type="email"
                onChange={props.setEmail}
              /&amp;gt;
            &amp;lt;/Form.Group&amp;gt;
            &amp;lt;Form.Group controlId="password-1"&amp;gt;
              &amp;lt;Form.ControlLabel&amp;gt;Password&amp;lt;/Form.ControlLabel&amp;gt;
              &amp;lt;Form.Control
                name="password"
                type="password"
                autoComplete="off"
                onChange={props.setPassword}
              /&amp;gt;
            &amp;lt;/Form.Group&amp;gt;
            &amp;lt;Form.Group&amp;gt;
              {props.error &amp;amp;&amp;amp; (
                &amp;lt;Message showIcon type="error"&amp;gt;
                  {props.error}
                &amp;lt;/Message&amp;gt;
              )}
            &amp;lt;/Form.Group&amp;gt;
            &amp;lt;ButtonToolbar&amp;gt;
              &amp;lt;Button appearance="primary" type="submit"&amp;gt;
                {props.isLogin ? "Login" : "Signup"}
              &amp;lt;/Button&amp;gt;
            &amp;lt;/ButtonToolbar&amp;gt;
          &amp;lt;/Form&amp;gt;
        &amp;lt;/Modal.Body&amp;gt;
        &amp;lt;Modal.Footer&amp;gt;
          &amp;lt;Button onClick={handleClose} appearance="primary"&amp;gt;
            Ok
          &amp;lt;/Button&amp;gt;
          &amp;lt;Button onClick={handleClose} appearance="subtle"&amp;gt;
            Cancel
          &amp;lt;/Button&amp;gt;
        &amp;lt;/Modal.Footer&amp;gt;
      &amp;lt;/Modal&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we imported the &lt;strong&gt;Modal&lt;/strong&gt;,&lt;strong&gt;Form&lt;/strong&gt;,&lt;strong&gt;Button&lt;/strong&gt;, &lt;strong&gt;Message&lt;/strong&gt;, &lt;strong&gt;ButtonToolbar&lt;/strong&gt; components to create a modal and form fields for users signup. We made this component reusable so that if we navigate to log in or signup the same Modal will be used for signup and login.&lt;/p&gt;

&lt;p&gt;Now update the code in the &lt;code&gt;App.js&lt;/code&gt;  to show this modal. First, import &lt;strong&gt;useState&lt;/strong&gt; and the &lt;strong&gt;AuthModal&lt;/strong&gt; component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
import { useState } from "react";
import { AuthModal } from "./components/AuthModal";
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add &lt;strong&gt;onClick&lt;/strong&gt; events to the login and signup nav.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;Nav.Item onClick={openLogin}&amp;gt;Login&amp;lt;/Nav.Item&amp;gt;
 &amp;lt;Nav.Item onClick={openSignup}&amp;gt;Signup&amp;lt;/Nav.Item&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create the state variables, the &lt;code&gt;openLogin&lt;/code&gt; ,&lt;code&gt;openSignUp&lt;/code&gt;, and the signup methods with the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
 const [open, setOpen] = useState(false);
  const [isLogin, setIsLogin] = useState(true);
  const [users, setUser] = useState([]);
  const [email, setEmail] = useState(null);
  const [password, setPassword] = useState(null);

  const signUp = () =&amp;gt; {
        setUser([...users, { email, password }]);
      };
  const openLogin = () =&amp;gt; {
    setOpen(true);
    setIsLogin(true);
  };

  const openSignup = () =&amp;gt; {
    setOpen(true);
    setIsLogin(false);
  }; 
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, Add the &lt;strong&gt;AuthModal&lt;/strong&gt; component in the &lt;strong&gt;Content&lt;/strong&gt; component and pass in the state variables and the methods as props to the &lt;strong&gt;AuthModal&lt;/strong&gt; component&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
 &amp;lt;Content&amp;gt;
  &amp;lt;AuthModal
    open={open}
    setOpen={setOpen}
    isLogin={isLogin}
    setEmail={setEmail}
    setPassword={setPassword}
    signUp={signUp}
  /&amp;gt;
&amp;lt;/Content&amp;gt;
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you go back to your browser, this time you should be able to open the signup modal.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F4RheF7R.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F4RheF7R.png" alt="Signup Modal"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Create Signin Form
&lt;/h2&gt;

&lt;p&gt;Now let's create and implement the logic to log a user in when they have signup into our application. In the   &lt;code&gt;App.js&lt;/code&gt; file, add the following state variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [error, setError] = useState(null);
const [isLoggedIn, setIsLoggedIn] = useState(false);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then create a &lt;strong&gt;login&lt;/strong&gt; method. In this method, we'll use the Javascript filter function to search for the record that matches the email and password provided by the user and reset the isLogin state or set an error message&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const login = () =&amp;gt; {
    const foundUser = users.filter(
      (user) =&amp;gt; user.email === email &amp;amp;&amp;amp; user.password === password
    );
    if (foundUser.length &amp;gt; 0) {
      setIsLoggedIn(true);
      setError(null);
    } else {
      setError("Email or Password is incorrect");
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we'll update the props in the AuthModal component with the state variables and login method we just created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;AuthModal
   open={open}
   setOpen={setOpen}
   isLogin={isLogin}
   setEmail={setEmail}
   setPassword={setPassword}
   error={error}
   login={login}
   signUp={signUp}
 /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if you open the login modal and try to log in as a user, you should the output below;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FkD44PQP.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FkD44PQP.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Open Source Session Replay
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.&lt;/em&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblog.openreplay.com%2Fstatic%2F0a3dcbea2c3ddf66242e78ffd2a65233%2F10931%2Fbanner-blog.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblog.openreplay.com%2Fstatic%2F0a3dcbea2c3ddf66242e78ffd2a65233%2F10931%2Fbanner-blog.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Start enjoying your debugging experience - &lt;a href="https://github.com/openreplay/openreplay" rel="noopener noreferrer"&gt;start using OpenReplay for free&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Create the Gallery component
&lt;/h2&gt;

&lt;p&gt;Now that we've been able to implement the login and signup features, Let's create our photo gallery. To do that, create a new component in the components folder, name it &lt;code&gt;Photo.jsx&lt;/code&gt; and add the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Row, Col } from "rsuite";

export const Photo = (props) =&amp;gt; {
  return (
    &amp;lt;Row&amp;gt;
      {props.photos.map((photo) =&amp;gt; {
        return (
          &amp;lt;Col md={4} key={photo.id}&amp;gt;
            &amp;lt;img
              src={photo.URL}
              alt={photo.name}
              onClick={() =&amp;gt; props.setOpenModal(true)}
            /&amp;gt;
          &amp;lt;/Col&amp;gt;
        );
      })}
    &amp;lt;/Row&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we imported the &lt;strong&gt;Row&lt;/strong&gt;, and *&lt;em&gt;Col *&lt;/em&gt; components from React Suite to define a row and column for the photos in our application. Then we loop the photos array (we'll create it shortly) using the Javascript map function and display the columns. Our photo array has the URL and name properties which store the name of the image and the URL respectively.&lt;/p&gt;

&lt;p&gt;Now in the &lt;code&gt;App.js&lt;/code&gt; file, import the &lt;strong&gt;Photo&lt;/strong&gt; component and create the photos array state variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
import { Photo } from "./components/Photo";

function App() {
...
const [photos, setPhotos] = useState([]);
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add the &lt;strong&gt;Photo&lt;/strong&gt; to the &lt;strong&gt;Content&lt;/strong&gt; component and pass in the required props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Content&amp;gt;
...
{isLoggedIn &amp;amp;&amp;amp; &amp;lt;Photo photos={photos}&amp;gt;&amp;lt;/Photo&amp;gt;}
&amp;lt;/Content&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we used the isLoggedIn state variable to check if the user is logged in before we render the Photo component.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create Add Photo component
&lt;/h2&gt;

&lt;p&gt;Now let's create another component to allow logged-in users to create and add new photos/images to the application. To do that, create a &lt;code&gt;PhotoModal.jsx&lt;/code&gt; file in the component folder and add the code snippet below;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Button, Modal, Form, ButtonToolbar } from "rsuite";
export const PhotoModal = (props) =&amp;gt; {
  const handleClose = () =&amp;gt; props.setOpenModal(false);
  return (
    &amp;lt;div className="modal-container"&amp;gt;
      &amp;lt;Modal open={props.openModal} onClose={handleClose}&amp;gt;
        &amp;lt;Modal.Header&amp;gt;
          &amp;lt;Modal.Title&amp;gt;Create New Photo&amp;lt;/Modal.Title&amp;gt;
        &amp;lt;/Modal.Header&amp;gt;
        &amp;lt;Modal.Body&amp;gt;
          &amp;lt;Form fluid onSubmit={props.addPhoto}&amp;gt;
            &amp;lt;Form.Group controlId="name"&amp;gt;
              &amp;lt;Form.Group controlId="name"&amp;gt;
                &amp;lt;Form.ControlLabel&amp;gt;Image URL&amp;lt;/Form.ControlLabel&amp;gt;
                &amp;lt;Form.Control
                  name="name"
                  onChange={(input) =&amp;gt; props.setName(input)}
                /&amp;gt;
                &amp;lt;Form.HelpText&amp;gt;Required&amp;lt;/Form.HelpText&amp;gt;
              &amp;lt;/Form.Group&amp;gt;
            &amp;lt;/Form.Group&amp;gt;
            &amp;lt;Form.Group controlId="image"&amp;gt;
              &amp;lt;Form.Group controlId="image"&amp;gt;
                &amp;lt;Form.ControlLabel&amp;gt;Image URL&amp;lt;/Form.ControlLabel&amp;gt;
                &amp;lt;Form.Control
                  name="name"
                  onChange={(input) =&amp;gt; props.setPhoto(input)}
                /&amp;gt;
                &amp;lt;Form.HelpText&amp;gt;Required&amp;lt;/Form.HelpText&amp;gt;
              &amp;lt;/Form.Group&amp;gt;
            &amp;lt;/Form.Group&amp;gt;
            &amp;lt;ButtonToolbar&amp;gt;
              &amp;lt;Button appearance="primary" type="submit"&amp;gt;
                Create
              &amp;lt;/Button&amp;gt;
            &amp;lt;/ButtonToolbar&amp;gt;
          &amp;lt;/Form&amp;gt;
        &amp;lt;/Modal.Body&amp;gt;
        &amp;lt;Modal.Footer&amp;gt;
          &amp;lt;Button onClick={handleClose} appearance="primary"&amp;gt;
            Ok
          &amp;lt;/Button&amp;gt;
          &amp;lt;Button onClick={handleClose} appearance="subtle"&amp;gt;
            Cancel
          &amp;lt;/Button&amp;gt;
        &amp;lt;/Modal.Footer&amp;gt;
      &amp;lt;/Modal&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we created another modal with form fields using the React suite components. Then we created a &lt;strong&gt;handleClose&lt;/strong&gt; method to handle the closing of the modal, and used other methods and props from the App component like the &lt;strong&gt;setPhoto&lt;/strong&gt;, &lt;strong&gt;setName&lt;/strong&gt;, and &lt;strong&gt;addPhoto&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now import the &lt;strong&gt;PhotoModal&lt;/strong&gt; component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
import { PhotoModal } from "./components/PhotoModal";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the following state variables and methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  ...
  const [openModal, setOpenModal] = useState(false);
  const [photo, setPhoto] = useState(null);
  const [name, setName] = useState(null);

  const addPhoto = () =&amp;gt; {
    setPhotos([...photos, { name, URL: photo }]);
  };

  const openPhotoModal = () =&amp;gt; {
    setOpenModal(true);
  };
 ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we created the photo and name variables to get the &lt;strong&gt;URL&lt;/strong&gt; and &lt;strong&gt;name&lt;/strong&gt; of the photo from the form fields. Then the &lt;strong&gt;addPhoto&lt;/strong&gt; method to add a new photo to the array of &lt;strong&gt;photos&lt;/strong&gt; and &lt;strong&gt;openPhotoModal&lt;/strong&gt; method to open the PhotoModal.&lt;/p&gt;

&lt;p&gt;Next, add the PhotoModal to the Content component and pass in the methods and properties as props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Content&amp;gt;
  ...
  &amp;lt;PhotoModal
      openModal={openModal}
      setOpenModal={setOpenModal}
      addPhoto={addPhoto}
      setPhoto={setPhoto}
      setName={setName}
    /&amp;gt;
&amp;lt;/Content&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, update the &lt;strong&gt;Create New&lt;/strong&gt; nav by adding an &lt;strong&gt;onClick&lt;/strong&gt; action which will allow the user to open the modal when they are logged in.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  {isLoggedIn &amp;amp;&amp;amp; &amp;lt;Nav.Item onClick={openPhotoModal}&amp;gt;Create New&amp;lt;/Nav.Item&amp;gt;}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can log in and add a new photo to the application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add Custom Styling.
&lt;/h2&gt;

&lt;p&gt;Now update the styles in the App.css file with the code below to give all the images/photos a fixed width.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;img{
  width: 100%;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then import the file into the &lt;code&gt;App.js&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./App.css";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Test Application
&lt;/h2&gt;

&lt;p&gt;I have added two more photos to the application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FW11hQZa.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FW11hQZa.jpg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Go ahead and add more to test it out.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;So far, you’ve created a Photo gallery application using React and React Suite components. We started with introducing new features in v5 and then creating a demo application. I believe practice makes a difference, so feel free to clone the Github repo for this project and extend the functionalities of the application.&lt;/p&gt;

&lt;p&gt;Bye for now, see you in the next one.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to Build Node.js REST API with MySQL</title>
      <dc:creator>mercicodes</dc:creator>
      <pubDate>Thu, 28 Apr 2022 06:02:48 +0000</pubDate>
      <link>https://forem.com/mercicodes/how-to-build-nodejs-rest-api-with-mysql-2k04</link>
      <guid>https://forem.com/mercicodes/how-to-build-nodejs-rest-api-with-mysql-2k04</guid>
      <description>&lt;p&gt;In this tutorial, you'll build a simple database for adding, updating, and removing todos, this tutorial will show you how to create a REST API with Express and MySQL. The GitHub repository for this project can be cloned to follow along. Let's get started, shall we?&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting started
&lt;/h2&gt;

&lt;p&gt;This tutorial is a hands-on demonstration. Be sure you have the following in place before getting started:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;MySQL Database installed&lt;/li&gt;
&lt;li&gt;Node.js installed&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is MySQL databases
&lt;/h2&gt;

&lt;p&gt;MySQL is an open-source relational database management system (RDBMS) (RDBMS). It's the most often used database system with PHP. MySQL is a cloud-native database solution that comes with full management. HeatWave, a built-in high-speed query accelerator, increases MySQL performance by 5400x.&lt;/p&gt;

&lt;p&gt;Oracle Corporation created, distributed, and maintained MySQL, which has the following functionalities.&lt;/p&gt;

&lt;p&gt;The data in a MySQL database is organized into tables with columns and rows.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;MySQL is a server-based database management system.&lt;/li&gt;
&lt;li&gt;MySQL is a great choice for both small and large projects.&lt;/li&gt;
&lt;li&gt;MySQL is a database system that is extremely quick, dependable, and simple to use. It makes use of normal SQL.&lt;/li&gt;
&lt;li&gt;MySQL runs on a variety of platforms.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Project Setup
&lt;/h2&gt;

&lt;p&gt;Now that we have explored what MySQL database is all about, let's dive into creating our RESTFul application. First, we need to create a folder for our project with the command below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir rest-todos &amp;amp;&amp;amp; cd rest-todos
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code will create a rest-todos folder and change the current directory to it. Then, using the command below, we'll create a new node.js project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we'll install the dependencies we require for our project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express MySQL cors

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating our Express server
&lt;/h2&gt;

&lt;p&gt;Now that we have our dependencies installed let's create an &lt;code&gt;app.js&lt;/code&gt; file and add the following code snippet below to it. We'll import the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const cors = require("cors");
const AppError = require("./appError");
const errorHandler = require("./errorHandler");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we create an app instance from express, using the express.json() middleware in our app to parse the URL encoded body. Finally, we make our API router middleware listen to incoming requests to the URL specified.&lt;/p&gt;

&lt;p&gt;Then, we check for URLs missing from our endpoints and throw a 404 error to the user if they're accessed. The global error handler will handler we will have it setup in a later section.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(api, router);

app.all("*", (req, res, next) =&amp;gt; {
 next(new AppError(`The URL ${req.originalUrl} does not exists`, 404));
});
app.use(errorHandler);

const PORT = 3000;
app.listen(PORT, () =&amp;gt; {
 console.log(`server running on port ${PORT}`);
});

module.exports = app;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  connecting to MySQL
&lt;/h2&gt;

&lt;p&gt;Now let's go ahead and set up our MySQL Database. First, we'll open our MySQL shell with the command below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mysql -u root -p
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command will prompt for your root password. Enter the password and press the Enter key to continue.&lt;/p&gt;

&lt;p&gt;Then, create a database from your MySQL shell with by running the SQL statements below.&lt;/p&gt;

&lt;h2&gt;
  
  
  CREATE DATABASE
&lt;/h2&gt;

&lt;p&gt;Then, create the tasklist table by running the SQL statements below. The table will have an id, name, status, date_created  fields. The id is the primary key of our table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE tasklist(id int NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL, 
status varchar(50), 
date_created DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
PRIMARY KEY (id));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create a &lt;code&gt;dbConfig.js&lt;/code&gt; file and add the following code snippets below to it to connect the application to MySQL database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mysql = require('mysql');
const connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "1234",
 database: "todo",
});

connection.connect();

module.exports = connection;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create our controllers
&lt;/h2&gt;

&lt;p&gt;Let's get started building our application's routes.&lt;/p&gt;

&lt;p&gt;Create a controllers folder in our project root directory, then an &lt;code&gt;app.js&lt;/code&gt; file in the controllers folder.&lt;/p&gt;

&lt;p&gt;Our global error handler and MySQL database connection will be imported first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const AppError = require("./appError");
const conn = require("./dbConfig");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next step is to setup our &lt;code&gt;getAll&lt;/code&gt; handler, which will retrieve all of the todos in our database. The MySQL query method will be used in this handler, which takes a SQL query and a callback function as inputs. We'll use the &lt;code&gt;AppError&lt;/code&gt; class to return an error to the user if an error happens during the operation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports.getAll = (req, res, next) =&amp;gt; {
 conn.query("SELECT * FROM tasklist", function (err, data, fields) {
   if(err) return next(new AppError(err))
   res.status(200).json({
     status: "success",
     length: data?.length,
     data: data,
   });
 });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create our &lt;code&gt;createTask&lt;/code&gt; handler to add new &lt;strong&gt;todos&lt;/strong&gt; to our database. First, we need to check if the user is sending an empty form  before saving the data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports.createTask = (req, res, next) =&amp;gt; {
 if (!req.body) return next(new AppError("No form data found", 404));
 const values = [req.body.name, "pending"];
 conn.query(
   "INSERT INTO tasklist (name, status) VALUES(?)",
   [values],
   function (err, data, fields) {
     if (err) return next(new AppError(err, 500));
     res.status(201).json({
       status: "success",
       message: "todo created!",
     });
   }
 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, to get our todos by IDs, we develop a getTask handler. First, we'll see if the id is supplied in the request field, and if it isn't, we'll return an error to the client.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports.getTask = (req, res, next) =&amp;gt; {
 if (!req.params.id) {
   return next(new AppError("No todo id found", 404));
 }
 conn.query(
   "SELECT * FROM tasklist WHERE id = ?",
   [req.params.id],
   function (err, data, fields) {
     if (err) return next(new AppError(err, 500));
     res.status(200).json({
       status: "success",
       length: data?.length,
       data: data,
     });
   }
 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, to update our todos, we'll write our updateTask handler, which will edit the todo whose id is in the request parameter to be completed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports.updateTask = (req, res, next) =&amp;gt; {
 if (!req.params.id) {
   return next(new AppError("No todo id found", 404));
 }
 conn.query(
   "UPDATE tasklist SET status='completed' WHERE id=?",
   [req.params.id],
   function (err, data, fields) {
     if (err) return next(new AppError(err, 500));
     res.status(201).json({
       status: "success",
       message: "todo updated!",
     });
   }
 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, to delete a todo from our database, we'll create a deleteTask handler. To delete a todo whose id is the request argument, we'll use the delete statement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports.deleteTask = (req, res, next) =&amp;gt; {
 if (!req.params.id) {
   return next(new AppError("No todo id found", 404));
 }
 conn.query(
   "DELETE FROM tasklist WHERE id=?",
   [req.params.id],
   function (err, fields) {
     if (err) return next(new AppError(err, 500));
     res.status(201).json({
       status: "success",
       message: "todo deleted!",
     });
   }
 );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create our Error handlers
&lt;/h2&gt;

&lt;p&gt;Now that we have all our API controllers setup, let's go ahead and create our error class function with the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AppError extends Error {
 constructor(msg, statusCode) {
   super(msg);

   this.statusCode = statusCode;
   this.error = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
   this.isOperational = true;

   Error.captureStackTrace(this, this.constructor);
 }
}
module.exports = AppError;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, without stopping our program, check for probable issues and deliver the associated error and status code to the client.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = (err, req, res, next) =&amp;gt; {
 err.statusCode = err.statusCode || 500;
 err.status = err.status || "error";
 res.status(err.statusCode).json({
   status: err.status,
   message: err.message,
 });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create routes
&lt;/h2&gt;

&lt;p&gt;Now let's create API routes to access our controllers. Create a router.js file and add the code snippets below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const controllers = require("./controllers");
const router = express.Router();

router.route("/").get(controllers.getAllTodos).post(controllers.createTodo);
router
 .route("/:id")
 .get(controllers.getTodo)
 .put(controllers.updateTodo)
 .delete(controllers.deleteTodo);
module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now update the app.js file to import our router with  the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
const router = require("./router")
app.use("task/", router);
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Throughout this tutorial, you've learned how to build a REST API in Node.js by creating a todo application. You add more features like authentication, and authorisation to the application you just built.&lt;/p&gt;

</description>
      <category>mysql</category>
      <category>rest</category>
    </item>
  </channel>
</rss>
