<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raz Levy on Medium]]></title>
        <description><![CDATA[Stories by Raz Levy on Medium]]></description>
        <link>https://medium.com/@raz-levy?source=rss-384c08383c4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ja1WAMwnUmeehQdofyl9Ig.jpeg</url>
            <title>Stories by Raz Levy on Medium</title>
            <link>https://medium.com/@raz-levy?source=rss-384c08383c4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:15:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raz-levy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tips I Wish I Knew As A Junior Developer]]></title>
            <link>https://raz-levy.medium.com/tips-i-wish-i-knew-as-a-junior-developer-4afda7479a9d?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4afda7479a9d</guid>
            <category><![CDATA[junior-developer]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[senior-developer]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[tips]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 13:47:00 GMT</pubDate>
            <atom:updated>2024-03-09T13:47:00.984Z</atom:updated>
            <content:encoded><![CDATA[<h2>12 Tips I Wish I Knew As A Junior Developer</h2><p>Being a junior developer isn’t an easy task those days, you have a lot of work to do and many things you should learn to be accepted to a role and succeed in your day-to-day job.<br>In this article, I summarized many tips I wish I knew as a junior developer. These tips will help you get started on the right foot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ilODlQ513nUwi9JB" /></figure><h4>1. Keep learning is a part of your job.</h4><p>The field of technology is constantly evolving. New programming languages, frameworks, tools, and methodologies are regularly introduced. Staying current with these developments ensures you can leverage the latest and most efficient technologies in your work.</p><p>In addition to that, learning exposes you to different types of problems and their solutions. This helps you develop a broader perspective on problem-solving and equips you with the ability to approach challenges creatively and efficiently.</p><p>As a part of my B.Sc I wanted to learn many more things which weren’t a part of the original syllabus, so I took some online courses to develop my skills and be more relevant so I would be able to send my resume to many companies and get some interviews.</p><h4>2. Searching the internet is a very important skill, practice it as much as you can.</h4><p>Development often involves encountering problems and challenges that you haven’t faced before. The ability to search for solutions online allows you to tap into the vast knowledge available on the internet.</p><p>Many developers share their experiences and solutions on forums, blogs, and documentation like this one, providing valuable insights.<br>Another benefit from this tip is that in many cases you won’t need to depend on other teammates and you will be able to solve your problems by yourself.</p><p>A good resource may be <a href="https://stackoverflow.com/">https://stackoverflow.com</a> where a lot of developers ask questions and get answers for their issues from other developers and technology experts.</p><h4>3. Start small, then extend.</h4><p>When creating a new system, or adding a new feature to an existing system, I extremely recommend you start with a very simple version, with minimal functionality requirements, then extend this solution step-by-step until it fits all the original requirements.</p><p>Planning in detail a big task correctly at the beginning is super hard, instead, you can learn as you go, change your ideas, and understand what will be the best implementation later during your task.</p><h4>4. Change one thing at a time</h4><p>When developing a feature, or a part of it, and by accident breaking something, or changing its functionality, it’s super easy to follow your steps if you break the original task into smaller tasks, that do only one thing in each task.</p><p>Do one thing, make sure it works, and only then repeat.<br>Changing one time at a time is also vital for developers because it simplifies debugging, minimizes the risk of unintended consequences, and promotes a systematic approach to problem-solving.</p><h4>5. Add logging and error handling early in the development process</h4><p>Logs provide a detailed record of system behavior, helping developers trace the flow of execution and diagnose problems efficiently. Early error handling ensures that potential issues are captured and reported immediately, preventing them from escalating into more significant issues later.</p><p>By implementing these practices from the start, you will be able to establish a robust foundation for troubleshooting, enhancing the overall reliability and maintainability of the software throughout its lifecycle.</p><h4>6. Test everything you can</h4><p>Thorough testing is a critical aspect of the development process, allowing developers to identify and rectify potential issues before they impact the end-users.</p><p>Comprehensive testing ensures that each component of the software functions as intended and is compatible with other elements, contributing to a more robust and reliable system. Early and rigorous testing also reduces the likelihood of encountering unexpected challenges during later stages of development, saving time and resources, and also keeps you from publishing mistakes.</p><h4>7. Everything takes longer than you think</h4><p>In the realm of programming, tasks consistently consume more time than initially anticipated, and this tendency is particularly pronounced.</p><p>Estimating the duration of a feature’s development remains challenging, even in optimal conditions.<br>Unforeseen challenges often arise during software development, such as a seemingly straightforward merge introducing subtle bugs, necessitating modifications due to framework upgrades, or encountering unexpected issues with API calls.</p><h4>8. Understand the existing code before estimating</h4><p>Before making project estimates, it’s crucial to thoroughly understand the existing code. This ensures that you can spot any complexities or challenges hidden in the system before you start working on it.</p><p>By taking a close look at the current code, you can figure out how changes might affect the project, identify any dependencies, and anticipate potential issues.</p><p>This understanding is key to making informed decisions, setting realistic timelines, and allocating resources effectively, all of which contribute to the overall success and efficiency of the development process.</p><h4>9. Bugs will be there forever.</h4><p>Bugs are inevitable in software development, and “getting it right the first time” is unrealistic. Despite our best efforts, bugs inevitably surface because there are often aspects you won’t anticipate.</p><p>Instead of striving for perfection initially, it’s more practical to establish a system that facilitates swift troubleshooting, bug fixing, and deployment solutions.</p><h4>10. When trying to fix a bug, first, reproduce the problem.</h4><p>The very first step you should take when trying to fix a bug is to reproduce the problem.</p><p>Without the ability to reproduce the problem, you will grope in the dark and won’t really know what you should fix, or maybe even guess what to do without really understanding what is the problem.</p><p>After reproducing the bug, make sure that when the fix is added, the problem is gone and you won’t be able to reproduce it again.</p><h4>11. Use timestamps in your logs.</h4><p>When debugging, or looking at logs, it may be very difficult to find the right log due to multiple events fired at the same time, or a lot of trash logs that are available in debug mode.</p><p>By adding timestamps to your logs you will be able to follow your requests and debug your system efficiently.</p><h4>12. Ask. Always ask.</h4><p>Being a part of a team comes with a few benefits, one of them is the ability to brainstorm with other professional people, who are aware of your code and know what you are trying to do.</p><p>When you feel like you can’t find a solution to your problem, and after you tried to find a solution over the internet, cap it with a time, and when you get into that cap, raise a question to your teammates, you will be surprised how many opinions and answers you will get, different people are go through a different path, so everyone has a slightly different experience that can contribute to the situation.</p><h3>Wrapping up</h3><p>Reflecting on my experience, I’ve fathered essential insights that could have significantly benefited my early career. These lessons encompass the importance of continuous learning, navigating challenges systematically, and fostering resilience in the ever-evolving field of software development.<br>Embracing these principles can pave the way for a more effective and fulfilling journey in the realm of programming.</p><p>Want to read more helpful content?</p><ul><li><a href="https://javascript.plainenglish.io/battling-bugs-with-typescript-unit-testing-its-a-fun-damental-thing-125a0c84c63f">Battling Bugs with TypeScript Unit Testing — It’s a Fun(damental) Thing</a></li><li><a href="https://javascript.plainenglish.io/supercharge-your-typescript-skills-with-these-pro-tips-70fd896f4939">Supercharge Your TypeScript Skills with These Pro Tips</a></li><li><a href="https://raz-levy.medium.com/communicating-between-micro-frontends-using-custom-events-in-react-js-e3dab0571edb">Communicating between Micro Frontends using Custom Events in React.JS</a></li><li><a href="https://javascript.plainenglish.io/use-rbac-to-protect-your-reactjs-app-from-unauthorized-access-typescript-6a7a6a4dd465">Use RBAC to Protect Your ReactJS App from Unauthorized Access 🚫 ✅ (TypeScript)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4afda7479a9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Battling Bugs with TypeScript Unit Testing — It’s a Fun(damental) Thing]]></title>
            <link>https://javascript.plainenglish.io/battling-bugs-with-typescript-unit-testing-its-a-fun-damental-thing-125a0c84c63f?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/125a0c84c63f</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 12:17:16 GMT</pubDate>
            <atom:updated>2023-10-04T12:17:16.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>Battling Bugs with TypeScript Unit Testing — It’s a Fun(damental) Thing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*xmyT4DIcGW2JeGM-.jpg" /></figure><p>In this article, I’m going to dive into the exciting world of unit testing in TypeScript, exploring essential tools like Jest and Sinon that every developer should have in their testing toolkit. We’ll start by unraveling the mysteries of Jest and Sinon, shedding light on what makes them indispensable for writing robust and reliable code. Then, we’ll delve into the very heart of unit testing, deciphering why these tests are crucial for building stable systems and maintaining code quality.</p><p>But that’s not all; we’ll demystify terms like mock, stub, and spy, helping you understand when and how to use each of these techniques effectively. And to cap it all off, I’ll provide you with a treasure trove of 10 best practices that will take your TypeScript unit testing game to the next level.</p><h3>What is Jest?</h3><p>Jest is a popular (~22m weekly downloads) JavaScript testing framework created by Facebook (Meta). It’s known for its simplicity, zero-config setup, and built-in features like automatic mocking and parallel test execution.<br>Developers use Jest to write unit, integration, and snapshot tests, ensuring code reliability and functionality. Its interactive watch mode streamlines iterative development, making it a valuable tool for maintaining code quality.</p><h3>What are unit tests?</h3><p>Unit tests are a fundamental aspect of software development. They involve testing individual units or components of code in isolation to ensure they function as intended. These tests help catch bugs early in the development process, promote code modularity, and enhance overall code quality. By writing unit tests, developers can verify that each piece of code of their codebase performs its specific task correctly, leading to more robust and maintainable software.</p><p><strong>Examples of unit tests:</strong></p><ol><li>Input validation</li><li>Error handling</li><li>Functional correctness and completeness</li><li>Correctness of output data (returned value)</li></ol><h4>Unit testing ideals</h4><ol><li><strong>Isolated: </strong>Tests should be designed to isolate the specific piece of code or functionality that is being tested, ensuring that the test’s outcome is not affected by external factors or dependencies.</li><li><strong>Repeatable: </strong>Tests should consistently produce the same result when run multiple times, regardless of the environment or order in which they ar executed, providing reliability and predictability.</li><li><strong>Automatable: </strong>Tests should be easily automated, allowing them to be executed automatically as a part of a CI/CD pipeline, enabling rapid feedback on code changes.</li><li><strong>Easy to write: </strong>Tests should be straightforward to create and maintain, with clear and concise test cases that developers can write without excessive effort, promoting frequent testing as part of the development process.</li></ol><h3>Mock? Spy? Stub?</h3><p>In software testing, mock, spy, and stub are vital techniques. Mocks simulate objects, spies track function calls, and stub replace code behavior. These methods help control and verify interactions in unit tests, enhancing their effectiveness.</p><p>In the following section, I’m going to tell you a quick story, in which we are going to create multiple unit test cases, and by that, you will understand better the <strong>differences between mock, spy, and stub</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*tCUPYts0ef5kk6S6" /><figcaption>Your ice cream shop</figcaption></figure><p>So, let me transport you to a different scenario, where you are not a developer, but instead, you’re the owner of an ice cream shop.<br>You have a team of employees who work each day, and you want to ensure that they’re performing their duties according to your expectations.</p><p>In your shop, you have a few different ice cream flavors, so every potential customer can ask for whatever flavor he wants in his corn.</p><h4>Mocks</h4><p>According to our ice cream shop story, let’s say for example that you want to verify that the employee knows how to calculate the price in the cashier for whatever the customer chooses.<br>In order to do that, <strong>your employees don’t really have to actually put the ice cream in a corn and serve it to the customer.</strong></p><p>Now, let’s say that we have many different ice cream flavors in our store, in this case, we don’t want to rely on the pricing functionality, but we want to ensure that the employee knows how to calculate the sum of them in order to take the order correctly.</p><p>Here’s the calculation function:</p><pre>export function calculateTotalPrice(orderDetails) {<br>  let price = 0;<br><br>  orderDetails.forEach(partOfOrder, () =&gt; {<br>    price += getPrice(partOfOrder);<br>  });<br><br>  return price;<br>}</pre><p>In order to test this function, we won’t want to rely on the <strong>getPrice</strong> function, because <strong>it’s not a part of</strong> <strong>calculateTotalPrice</strong>’s functionality.<br>Instead, we’ll want to be in control of <strong>getPrice</strong> during our test, so we’ll mock it and implement the prices for each of the flavors.</p><pre>import { calculateTotalPrice } from &quot;./iceCreamShop&quot;;<br>import * as priceLookup from &quot;./priceLookup&quot;;<br><br>const mockGetPrice = jest.spyOn(priceLookup, &quot;getPrice&quot;);<br><br>mockGetPrice.mockImplementation((flavor) =&gt; {<br>  if (flavor === &quot;Vanilla&quot;) return 2.5;<br>  if (flavor === &quot;Chocolate&quot;) return 3.0;<br>});<br><br>test(&quot;calculateTotalPrice calculates the correct total&quot;, () =&gt; {<br>  const order = [<br>    { flavor: &quot;Vanilla&quot;, quantity: 2 },<br>    { flavor: &quot;Chocolate&quot;, quantity: 1 }<br>  ];<br><br>  const total = calculateTotalPrice(order);<br>  <br>  expect(total).toBe(8.0);<br>});</pre><p>In the following example, you can see that I’ve implemented a mock of the <strong>getPrice</strong> function, in order to be in control of it, so I can be 100% of the expected result while I’m testing calculateTotalPrice, and not rely on external functionality.</p><h4><strong>Spy</strong></h4><p>Let’s say that you’re curious about how many times your employee eats ice cream when you’re not looking.<br>Now think of a real-life scenario, how can we verify that? we’ll probably want to spy on the employee without his knowing that he’s being spied on.</p><p><strong>Spy helps you to follow a function without actually changing it</strong>, meaning that you don’t have to change the implementation for a function in order to ask questions about its behavior.</p><pre>// shop.js<br>export function serveIceCream(flavor) {<br>  console.log(`Serving ${flavor} ice cream`);<br>  <br>  const price = getPrice(flavor);<br>  <br>  console.log(`Price of ${flavor} is ${price}`);<br>}<br><br>// shop.test.js<br>import * as iceCreamShop from &quot;./shop&quot;;<br><br>test(&quot;getPrice be called with correct arguments&quot;, () =&gt; {<br>  const spy = jest.spyOn(iceCreamShop, &quot;getPrice&quot;);<br><br>  iceCreamShop.serveIceCream(&quot;Vanilla&quot;);<br>  iceCreamShop.serveIceCream(&quot;Chocolate&quot;);<br><br>  expect(spy).toHaveBeenCalledTimes(2);<br>  expect(spy).toHaveBeenCalledWith(&quot;Vanilla&quot;);<br>  expect(spy).toHaveBeenCalledWith(&quot;Chocolate&quot;);<br>});</pre><p>In the following example, we’re not changing the implementation logic of getPrice, but we’re verifying that it was called correctly, by checking that the arguments that it was called with are correct and as I expected them to be.</p><h4>Stub</h4><p>Let’s say that your employee can make different flavors of ice cream, but today you want him to be able to serve only Vanilla flavor.<br>In order to do that, you can change the abilities of your employee and put in his hand a pretend ice cream scoop that can make only Vanilla flavor.</p><p><strong>Stub helps you make something behave in a specific way, even if it can do more.</strong></p><p>Here are a few examples of when you’ll want to implement a stub:<br>- Throw errors from functions in a proactive manner.<br>- Replace API calls in order not to rely on external dependencies.<br>- Replace problematic pieces of code.</p><p>In order to stub, I’m going to use <a href="https://sinonjs.org/"><strong>SinonJS</strong></a>, which is a well-documented incredible testing library that works with most of the testing frameworks and makes stub very easy and smooth.</p><p>In order to install Sinon, use the following script:</p><pre>npm install --save-dev sinon @types/sinon</pre><pre>// priceLookup.js<br>export async function getPrice(flavor) {<br>  const priceResponse = await axios.get(`/price?name=${flavor.name}`);<br>  const { amount } = priceResponse.data;<br>  <br>  console.log(`The price of ${flavor.name} is ${amount}`);<br><br>  return amount;<br>}<br><br>// priceLookup.test.js<br>import * as priceLookup from &quot;./priceLookup&quot;;<br>import sinon from &quot;sinon&quot;;<br><br>test(&quot;getPrice should return the price&quot;, async () =&gt; {<br>  const PRICE_TO_STUB = 3.0;<br>  sinon.stub(priceLookup, &quot;getPrice&quot;).resolves(PIRCE_TO_STUB);<br><br>  const price = await getPrice(&quot;Vanilla&quot;);<br><br>  expect(price).toBe(PRICE_TO_STUB);<br>});</pre><p>In this example, as you can see my function getPrice depends on the returned value of the axios HTTP request, which I don’t want to rely on during my tests, instead, I stub it and return a value that I expect to get from the network call.</p><p>Another example may be throwing an error from the getPrice function, and verifying that the the function knows how to handle the error or bubbles it up.</p><h3>Testing Best Practices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*r0K2K5yKrQ4PXp_gpoiWMw.png" /></figure><h4>Use the AAA Pattern</h4><p><strong>AAA</strong> stands for:</p><ul><li><strong>Arrange — </strong>Set up the required test preconditions in order to take action.</li><li><strong>Act</strong> — The ‘meat’ of the test, the action that you want to test.</li><li><strong>Assert</strong> — Where you make sure that the result of the action is what you expected.</li></ul><p>By using the AAA pattern, you will make your and your partner&#39;s lives easier by understanding the tests and handling them easily in case of failures.</p><pre>test(&quot;should call getItem from LocalStorage&quot;, () =&gt; {<br>  // Arrange: Initialize spy and test subject<br>  const getItemSpy = jest.spyOn(obj, &quot;getItem&quot;);<br>  const service = new PreferencesService({ getItem: getItemSpy } as LocalStorage);<br><br>  // Act: Call getPreferences<br>  service.getPreferences(&quot;test key&quot;);<br>  <br>  // Assert: Make sure it called the spy<br>  expect(getItemSpy).toHaveBeenCalled();<br>});</pre><h4>Don’t Use Magic Values</h4><p>Magic values are hard-coded values that appear directly in your code without explanation or context. These values are considered “magic” because their meaning or significance is not immediately apparent to someone reading the code. They can be problematic for several reasons, especially when used in unit tests.</p><p>Instead of writing the test this way:</p><pre>it(&quot;should sum two numbers&quot;, () =&gt; {<br>  expect(sum(2,3)).toBe(5);<br>});</pre><p>Do it that way:</p><pre>it(&quot;should sum two numbers, () =&gt; {<br>  const ANY_FIRST_NUMBER = 2;<br>  const ANY_SECOND_NUMBER = 3;<br><br>  expect(sum(ANY_FISRT_NUMBER, ANY_SECOND_NUMBER))<br>  .toBe(ANY_FIRST_NUMBER + ANY_SECOND_NUMBER);<br>});</pre><h4>Tests should be SIMPLE</h4><p>Simple unit tests are crucial for clarity, quick development, and easy maintenance. They reduce cognitive load, streamline debugging, and enhance collaboration among developers.</p><p>Try to create the smallest tests you can and try to leave them as lean and clean as you can.</p><h4>Organize your tests like telling a story</h4><p>This pattern provides clarity and context to your tests, making them easier to understand. It helps convey the expected behavior of the code being tested in a natural and human-readable way. This approach also encourages a focus on the behavior of the system, rather than implementation details, which can lead to more robust and maintainable tests.<br>Additionally, narrative-style tests are often more accessible to non-technical stakeholders, such as product managers or clients, who can better grasp the intended functionality of the software.</p><p>Instead of writing the test this way:</p><pre>it(&quot;Test accordion&quot;, () =&gt; {...});<br>it(&quot;Test buttons and icons&quot;, () =&gt; {...});</pre><p>Do it that way:</p><pre>describe(&quot;Accordion&quot;, () =&gt; {<br>  it(&quot;should open and close on click&quot;, () =&gt; {...});<br><br>  it(&quot;should close on click outside&quot;, () =&gt; {...});<br>});<br><br>describe(&quot;Button&quot;, () =&gt; {<br>  it(&quot;should be able to pass a callback function&quot;, () =&gt; {...});<br><br>  it(&quot;should be able to set secondary color&quot;, () =&gt; {...});<br>});</pre><h4>Test what should not happen</h4><p>Testing what should not happen, or negative testing, is vital because it uncovers vulnerabilities and unexpected behavior in your software. While position testing confirms the expected behavior, negative testing exposes how your code handles invalid inputs or errors, improving overall robustness and security.</p><p>For example:</p><pre>describe(&quot;Accordion&quot;, () =&gt; {<br>  it(&quot;should open and close on click&quot;, () =&gt; {...});<br><br>  // Add this kind of tests as well<br>  it(&quot;should not open when page loads&quot;, () =&gt; {...});<br>});</pre><h4>Create deterministic tests</h4><p>Creating deterministic tests is a good pattern because it ensures consistent and reliable test outcomes, enhancing confidence in your code’s correctness and stability. Deterministic tests eliminate randomness or external dependencies, making test results predictable and reproducible. This predictability aids in debugging and helps detect issues early in the development process, fostering a more efficient and trustworthy testing environment.</p><p>Instead of writing the test this way:</p><pre>it(&#39;should test a random number generator&#39;, () =&gt; {<br>  const randomValue = generateRandomNumber();<br>  assert.ok(randomValue &gt;= 0 &amp;&amp; randomValue &lt;= 100);<br>});</pre><p>This test is bad because it relies on a random number generator, making the outcome unpredictable and non-deterministic.</p><p>Do it that way:</p><pre>it(&#39;should correctly calculate the square of a number&#39;, () =&gt; {<br>  const result = calculateSquare(5);<br>  assert.strictEqual(result, 25);<br>});</pre><h4>Make dynamic tests and verify on multiple inputs</h4><p>Creating dynamic tests with multiple inputs is crucial because it helps verify the robustness and versatility of your code. These tests evaluate how your software performs across various scenarios, uncovering potential issues and edge cases that might otherwise remain hidden. By assessing multiple inputs, you ensure that your code functions reliably under different conditions, enhancing the overall quality and resilience of your software.</p><p>For example:</p><pre>describe(&#39;Rectangle Area Calculation&#39;, () =&gt; {<br>  test.each([<br>    [5, 10, 50],<br>    [3, 7, 21],<br>    [0, 100, 0],<br>    [8, 8, 64],<br>    [2.5, 4.5, 11.25],<br>  ])(<br>    &#39;should calculate the area correctly for length %p and width %p&#39;,<br>    (length, width, expectedArea) =&gt; {<br>      const calculatedArea = calculateRectangleArea(length, width);<br>      expect(calculatedArea).toBe(expectedArea);<br>    }<br>  );<br>});</pre><h4>Use Sinon’s Sandbox</h4><p>Leveraging Sinon’s sandbox in your test files offers numerous advantages. It allows you to isolate the code you’re testing from external dependencies, ensuring that your tests focus solely on the specific functionality you’re examining. The sandbox also simplifies the process of setting up and tearing down test doubles such as spies, stubs, and mocks, streamlining your test code and making it more readable. Moreover, using a sandbox makes it easier to avoid potential side effects and conflicts that can arise when multiple tests interact with the same functions or methods. Ultimately, this approach promotes more robust and maintainable tests that accurately assess the behavior of your code.</p><p>For example:</p><pre>describe(&#39;Sandbox Example&#39;, function () {<br>  it(&#39;should stub a function using Sinon sandbox&#39;, function () {<br>    const sandbox = sinon.createSandbox();<br>    // Stubbing the calculateTotalPrice function<br>    sandbox.stub(global, &#39;calculateTotalPrice&#39;).returns(42);<br><br>    const result = calculateTotalPrice(10, 3);<br><br>    assert.strictEqual(result, 42);<br><br>    // Restoring the original function<br>    sandbox.restore();<br>  });<br>});</pre><h4>Don’t rely on network calls</h4><p>Avoiding reliance on network calls in tests is crucial to prevent issues such as slow test execution, network outages, and changes in external services, which can lead to test failures. It ensures test stability, speed, and reliability, promoting a controlled and portable testing environment.</p><p>if you’re working with Node.js and need to mock HTTP requests and responses in your tests, consider using the node-mocks-http NPM library. It provides a convenient and reliable way to simulate HTTP interactions in your tests, allowing you to thoroughly validate your code&#39;s behavior without relying on actual network calls. Additionally, this library can be a valuable asset for testing web applications, APIs, and middleware components in a controlled environment.</p><p><a href="https://www.npmjs.com/package/node-mocks-http">Link to node-mocks-http in NPM</a></p><h4>Never duplicate implementation logic</h4><p>Avoid duplicating implementation logic in tests to ensure maintainability and consistency. Duplications lead to errors and complicated updates. Centralized logic in test utilities simplifies maintenance and promotes robust testing.</p><p>Take this function for example:</p><pre>function calculateTotalPrice(items) {<br>  let totalPrice = 0;<br>  items.forEach((item) =&gt; {<br>    totalPrice += item.price;<br>  });<br>  return totalPrice;<br>}</pre><p>Instead of writing this test:</p><pre>test(&quot;Calculate total price correctly for multiple items&quot;, () =&gt; {<br>  const items = [<br>    { name: &quot;Item A&quot;, price: 10 },<br>    { name: &quot;Item B&quot;, price: 15 },<br>    { name: &quot;Item C&quot;, price: 8 },<br>  ];<br><br>  let totalPrice = 0;<br>  items.forEach((item) =&gt; {<br>    totalPrice += item.price;<br>  });<br><br>  expect(totalPrice).toBe(33);<br>});</pre><p>Do it that way:</p><pre>test(&quot;Calculate total price correctly for multiple items&quot;, () =&gt; {<br>  const items = [<br>    { name: &quot;Item A&quot;, price: 10 },<br>    { name: &quot;Item B&quot;, price: 15 },<br>    { name: &quot;Item C&quot;, price: 8 },<br>  ];<br><br>  const totalPrice = calculateTotalPrice(items);<br><br>  expect(totalPrice).toBe(33);<br>});</pre><p>Want to read more helpful content?</p><ul><li><a href="https://javascript.plainenglish.io/supercharge-your-typescript-skills-with-these-pro-tips-70fd896f4939">Supercharge Your TypeScript Skills with These Pro Tips</a></li><li><a href="https://raz-levy.medium.com/communicating-between-micro-frontends-using-custom-events-in-react-js-e3dab0571edb">Communicating between Micro Frontends using Custom Events in React.JS</a></li><li><a href="https://raz-levy.medium.com/how-to-implement-sessions-using-nodejs-and-mongodb-56266bfd19c3">How to Implement Sessions using NodeJS and MongoDB</a></li></ul><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/XxRS92b2"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=125a0c84c63f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/battling-bugs-with-typescript-unit-testing-its-a-fun-damental-thing-125a0c84c63f">Battling Bugs with TypeScript Unit Testing — It’s a Fun(damental) Thing</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your TypeScript Skills with These Pro Tips]]></title>
            <link>https://javascript.plainenglish.io/supercharge-your-typescript-skills-with-these-pro-tips-70fd896f4939?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/70fd896f4939</guid>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 12:16:02 GMT</pubDate>
            <atom:updated>2023-07-20T12:16:02.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBnxfDMvVthn92DOcIsqVw.png" /></figure><h4>Use unknown type before fallback into any</h4><p>As you already know, using the any type in TypeScript is not so clean 🧹</p><p>As version 3.0, TypeScript introduced a new keyword called unkown .<br>The unknown type in TypeScript provides safer handling of variables with unknown types.<br>Promoting stricter type checks and early error detecting, making it preferable to the any type.</p><pre>let unknownValue: unknown = &#39;Some string&#39;;<br>let anyValue: any = &#39;Some string&#39;;<br><br>const booleanValue: boolean = unkownValue // Type &#39;unknown&#39; is not assignable to type &#39;boolean&#39;<br>const booleanValue: boolean = anyValue // Works</pre><h4>Avoid type assertions</h4><p>Avoid type assertions in TypeScript to maintain code integrity. They bypass type checking, risking runtime errors and compromising type safety. Prioritizing proper type annotations ensures robustness and reduces unexpected issues.</p><p>If you’re using TypeScript correctly, you shouldn’t find yourself using type assertions often (i.e <strong>value</strong> as <strong>type</strong>).</p><pre>type TFuel = &#39;disel&#39; | &#39;gasoline&#39;;<br><br>interface ICar {<br>  model: string;<br>  year: number;<br>  fuelType: TFuel;<br>}<br><br>function isUsingDisel(car: ICar) {<br>  return car.fuelType === &#39;disel&#39;;<br>}<br><br>function isUsingGasoline(car: ICar) {<br>  return car.fuelType === &#39;gasoline&#39;;<br>}<br><br>const cars: ICar[] = getCars();<br><br>// error because typescript doesn&#39;t know the filtering<br>// narrows typing<br>const diselCars: ICar[] = cars.filter(isUsingDisel);<br><br>// you may be inclined to add an assertion:<br>const diselCards = cars.filter(isUsingDisel) as ICar[];</pre><h4>Use Generic Types Wisely</h4><p>Generics in TypeScript are a powerful feature that brings flexibility and reusability to code.<br>They introduce type parameters, enabling developers to write highly adaptable and type-safe functions, classes, and interfaces.<br>Generics allow for writing code that can handle multiple data types without sacrificing type checking.</p><pre>class Queue&lt;T&gt; {<br>  private elements: T[] = [];<br><br>  enqueue(element: T) {<br>    this.elements.push(element);<br>  }<br><br>  dequeue(): T | undefined {<br>    return this.elements.shift();<br>  }<br><br>  size(): number {<br>    return this.elements.length;<br>  }<br>}<br><br>// Usage<br>const numbersQueue = new Queue&lt;number&gt;();<br>numberQueue.enqueue(10);<br>numberQueue.enqueue(20);<br>numberQueue.enqueue(30);<br><br>console.log(numberQueue.dequeue()); // Output: 10<br>console.log(numberQueue.size()); // Output: 2<br><br>const stringsQueue = new Queue&lt;string&gt;();<br>stringsQueue.enqueue(&quot;Hello&quot;);<br>stringsQueue.enqueue(&quot;World&quot;);<br><br>console.log(numberQueue.dequeue()); // Output: &quot;Hello&quot;<br>console.log(numberQueue.size()); // Output: 1<br><br>stringsQueue.enqueue(2); // TypeScript will throw a compilation error.</pre><h4>Get to Know Advanced Types</h4><p><strong>Mapped Types<br></strong>Mapped types in TypeScript bring an element of magic by dynamically transforming existing types based on their properties. They offer exciting possibilities for automating repetitive tasks and generating new types effortlessly.</p><pre>type Readonly&lt;T&gt; = {<br>  readonly [K in keyof T]: T[K];<br>}<br><br>interface Person {<br>  name: string;<br>  age: number;<br>}<br><br>type ReadonlyPerson = Readonly&lt;Person&gt;;<br><br>const person: ReadyonlyPerson = {<br>  name: &quot;Alice&quot;,<br>  age: 25<br>}<br><br>person.name = &quot;Bob&quot;; // Compilation error: Cannot assign to &#39;name&#39; because it is a read-only property.</pre><p><strong>Conditional Types<br></strong>Those types offer dynamic type creation based on conditions, akin to the ternary operator. They enhance flexibility, enabling tailored and adaptable type definitions with a concise syntax.</p><pre>type Check&lt;T&gt; = T extends number ? &quot;Number&quot; : &quot;Not a number&quot;;<br><br>type Result1 = Check&lt;5&gt;; // Result1 is &quot;Number&quot; because 5 is a number<br>type Result2 = Check&lt;&quot;Hello&quot;&gt; // Result2 is &quot;Not a number&quot; because &quot;Hello&quot; is not a number</pre><p>In this example, we define a conditional type Check&lt;T&gt; . the type Check&lt;T&gt; checks whether the type T extends number . If it does, the resulting type is set the “Number” , otherwise, it is set to “Not a number” .</p><p>Read more important and helpful content:</p><ul><li><a href="https://raz-levy.medium.com/communicating-between-micro-frontends-using-custom-events-in-react-js-e3dab0571edb">Communicating between Micro Frontends using Custom Events in React.JS</a></li><li><a href="https://raz-levy.medium.com/how-to-implement-sessions-using-nodejs-and-mongodb-56266bfd19c3">How to Implement Sessions using NodeJS and MongoDB</a></li><li><a href="https://javascript.plainenglish.io/use-rbac-to-protect-your-reactjs-app-from-unauthorized-access-typescript-6a7a6a4dd465">Use RBAC to Protect Your ReactJS App from Unauthorized Access 🚫 ✅ (TypeScript)</a></li></ul><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70fd896f4939" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/supercharge-your-typescript-skills-with-these-pro-tips-70fd896f4939">Supercharge Your TypeScript Skills with These Pro Tips</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using React Forward Ref for Better Component Communication ]]></title>
            <link>https://javascript.plainenglish.io/using-react-forward-ref-for-better-component-communication-6b1b843de852?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b1b843de852</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[forwardref]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Sun, 14 May 2023 08:41:43 GMT</pubDate>
            <atom:updated>2023-05-14T08:41:43.482Z</atom:updated>
            <content:encoded><![CDATA[<p>As a developer, you may have built at least a few components and needed to interact with them differently, including sending props, changing their values, and <strong>controlling them from a parent component</strong>.<br>There are many technics to control components. <strong>One of them is by forwarding a reference to the component from its parent.</strong></p><p>In order to control an HTML element with React.JS, we can simply set a reference to the element, and control the reference in order to change some functionality in the element.</p><p>When we want to control a <strong>ReactJS Component</strong>, we won’t be able to pass the reference as a prop without some changes to the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*akwuZDZrv0xsCb_Yj8iAmQ.png" /></figure><h4><strong>Background</strong></h4><p>In this tutorial, I will guide you on how to forward a reference to an existing component which is going to be a basic input component, that will be wrapped by a single div HTML element, and by using React’s forwardRef function we’ll pass a reference to the component, which will use for the input field and will allow us to control it.</p><h4>Prerequisites</h4><ol><li>Basic knowledge of JavaScript.</li><li>Basic knowledge of ReactJS.</li><li>An empty React.JS project (or simply usenpx create-react-app forward-ref-democommand in your terminal)</li></ol><h4>What is forwardRef</h4><blockquote>Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries. <strong>(reactjs.org)</strong></blockquote><h4>Creating the application</h4><p>First, create a text input component</p><pre>// /components/TextInput.js<br><br>import React from &quot;react&quot;;<br><br>const TextInput = () =&gt; (<br>  &lt;div&gt;<br>    &lt;input type=&quot;text&quot; /&gt;<br>  &lt;/div&gt;<br>);<br><br>export default TextInput;</pre><p>The component is very simple, it implements a div HTML element, and inside of it an input HTML element with a type of text.</p><p>Next, let’s implement the main application page:</p><pre>// App.js<br><br>import TextInput from &quot;./components/TextInput&quot;;<br>import &quot;./styles.css&quot;;<br><br>export default function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;TextInput /&gt;<br>      &lt;button&gt;Click me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>On this page, I’ve implemented the TextInput we just created and another button with <strong>Click me</strong> text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*b_LbzAb1jZEyVtimW7ZgQA.png" /></figure><blockquote><strong><em>Our mission: Get the input field focused when the button is being clicked.</em></strong></blockquote><h4>Using forwardRef</h4><p>To achieve our goal, we need to pass a reference to the TextInput component, but <strong>we can’t because none of the elements in the TextInput component will be able to receive it.</strong></p><p>Still, we have to achieve this goal, and for those use cases, we need forwardRef function, let’s implement it.</p><p>First, we need to create a reference that we will be able to pass.</p><pre>import { useRef } from &quot;react&quot;;<br>import TextInput from &quot;./components/TextInput&quot;;<br>import &quot;./styles.css&quot;;<br><br>export default function App() {<br>  const ref = useRef(null);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;TextInput /&gt;<br>      &lt;button&gt;Click me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>By using the <strong>useRef</strong> hook, we can create a new reference.</p><p>Next, let’s create the onClick function for the button element.</p><pre>import { useRef } from &quot;react&quot;;<br>import TextInput from &quot;./components/TextInput&quot;;<br>import &quot;./styles.css&quot;;<br><br>export default function App() {<br>  const ref = useRef(null);<br><br>  const onClickButton = () =&gt; {<br>    ref.current?.focus();<br>  }<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;TextInput /&gt;<br>      &lt;button onClick={onClickButton}&gt;Click me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Since we already know that we’re going to pass <strong>ref</strong> as a reference, the only thing that the button has to do is to set a focus for referenced element.</p><p>Next, let’s handle the TextInput component:</p><pre>import React, { forwardRef } from &quot;react&quot;;<br><br>const TextInput = forwardRef((_props, ref) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;input ref={ref} type=&quot;text&quot; /&gt;<br>    &lt;/div&gt;<br>  )<br>});<br><br>export default TextInput;</pre><p>In order to implement the forwardRef function, we need to make a small change to the TextInput component.</p><p>I’ve changed the declaration of the function and added the forwardRef, which receives 2 params, the first one is the props that the component can interact with, and the second one is the reference prop.</p><p>Next, all we have to do it to pass the reference prop to the HTML input element, in order to control it.</p><h4>Forward the actual reference</h4><pre>import { useRef } from &quot;react&quot;;<br>import TextInput from &quot;./components/TextInput&quot;;<br>import &quot;./styles.css&quot;;<br><br>export default function App() {<br>  const ref = useRef(null);<br><br>  const onClickButton = () =&gt; {<br>    ref.current?.focus();<br>  }<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;TextInput ref={ref}/&gt;<br>      &lt;button onClick={onClickButton}&gt;Click me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>To make everything work, all you have to do now is to pass the <strong>ref</strong> prop to the TextInput element just like you’d do with a regular HTML element.</p><h4>That’s it! You have implemented a React component and forwarded a reference to it!</h4><p><strong>Did you like it? Read more articles like this one</strong></p><ul><li><a href="https://javascript.plainenglish.io/use-rbac-to-protect-your-reactjs-app-from-unauthorized-access-typescript-6a7a6a4dd465">Use RBAC to Protect Your ReactJS App from Unauthorized Access 🚫 ✅ (TypeScript)</a></li><li><a href="https://raz-levy.medium.com/communicating-between-micro-frontends-using-custom-events-in-react-js-e3dab0571edb">Communicating between Micro Frontends using Custom Events in React.JS</a></li><li><a href="https://raz-levy.medium.com/how-to-upload-files-to-aws-s3-from-the-client-side-using-react-js-and-node-js-660252e61e0">How to upload files to AWS S3 from the client-side using React.JS and Node.JS</a></li><li><a href="https://raz-levy.medium.com/build-a-dynamic-modal-component-for-react-js-8ef32bdf6604">Build a Dynamic Modal Component for React JS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b1b843de852" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/using-react-forward-ref-for-better-component-communication-6b1b843de852">Using React Forward Ref for Better Component Communication 💬</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use RBAC to Protect Your ReactJS App from Unauthorized Access  ✅ (TypeScript)]]></title>
            <link>https://javascript.plainenglish.io/use-rbac-to-protect-your-reactjs-app-from-unauthorized-access-typescript-6a7a6a4dd465?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a7a6a4dd465</guid>
            <category><![CDATA[restricted]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 05:16:58 GMT</pubDate>
            <atom:updated>2023-04-12T05:16:58.860Z</atom:updated>
            <content:encoded><![CDATA[<h4>Background</h4><p>As a developer, you may have built a few applications during your professional life.</p><p><strong>Have you ever faced situations when you needed to hide important information from anonymous users</strong> who never sign-up for your application?</p><p>Did you ever think to yourself “<strong>How can I prevent from user X an action that I want to allow for user Y</strong>”?</p><p>This is exactly where <strong>RBAC</strong> takes its place and shines.<br>Using RBAC, you can create privileges in your app, and in this tutorial, I’m going to guide you on how to implement and use it, and by this, control the users which are using your application!</p><p><strong>What to pass the instructions and jump into code? </strong><a href="https://github.com/RLeDEV/react-rbac-example">The source code is here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qa4XqJhjeYMvE4hMu1Sozw.png" /></figure><h4><strong>Prerequisites</strong></h4><ol><li>Basic knowledge of JavaScript &amp; TypeScript.</li><li>Basic knowledge of ReactJS with styled-components installed.</li><li>A project with basic navigation between pages (<a href="https://github.com/RLeDEV/react-rbac-example/tree/master/src/routes">Inspiration</a>).</li></ol><h4><strong>What is RBAC</strong></h4><p>RBAC stands for Roll-Based Access Control and it describes a process by which you give permission to a user based on its access rights.</p><p>What it actually means is that you can give users access rights only to the resources that they are allowed to use or see and prevent them from seeing other resources that they don’t need or have access to.</p><p>You can take this blog post for example, only the author (me in this case) of the post, has the right to edit it and can see the edit button, but everyone else (you in this case) can only see it.</p><h4>Preventing Route Access</h4><p>First things first, we need to prevent users which are not allowed to entering protected routes.</p><p>To do so, we need first to create a Protected Route <a href="http://High Order Component">HOC</a> which will open the URL only when the requested user passes an authentication and authorization check.</p><p>In order to create a protected route, you need to install react-router-dom v6 using the following CLI command:</p><pre>npm install react-router-dom</pre><p>Next, create your routes — If you need help with that, you can use <a href="https://reactrouter.com/en/main/start/examples">react-router-dom examples</a> from their official documentation, or from <a href="https://github.com/RLeDEV/react-rbac-example/tree/master/src/routes">my example</a> in GitHub.</p><p>Make sure you define your routes using the following TypeScript type:</p><pre>export type TProtectRouteProps = {<br>    isAuthenticated: boolean;<br>    authenticationPath: string;<br>    outlet: JSX.Element<br>};</pre><p>When finished, you will have to create a new file called <strong>protectedRoute.tsx</strong> and fill inside the following code:</p><pre>import {FC} from &quot;react&quot;;<br>import {Navigate} from &quot;react-router-dom&quot;;<br>import {TProtectRouteProps} from &quot;../types&quot;;<br><br>/**<br>  @description Secured route which will display the content only if a user is authenticated<br>  @isAuthenticated boolean Describes whether a user is authenticated or not<br>  @authenticationPath string Route to authentication page<br>  @outlet JSX.Element Component that should be shown if user is authenticated<br>**/<br>const ProtectRoute: FC&lt;TProtectRouteProps&gt; = ({isAuthenticated, authenticationPath, outlet}) =&gt; {<br>    if (isAuthenticated) {<br>        return outlet;<br>    } else {<br>        return &lt;Navigate to={{pathname: authenticationPath}} /&gt;<br>    }<br>}<br><br>export default ProtectRoute;</pre><h4>User Context</h4><p>Until this point, all we did was prevent users from navigating to and between protected pages.</p><p>The reason we needed this part is that we wanted to ensure that we have the user object which will contain his permissions in the future.</p><p>Next, we will have to create a user context that will share the user details between the pages and will allow us to display the user privileges where needed.</p><p><strong>Types:</strong></p><p>First, let’s create the related interfaces, types, and enums:</p><pre>// /types/index.tsx<br><br>export enum Features {<br>  FEATURE_A = &#39;FEATURE_A&#39;<br>}<br><br>export enum Permissions {<br>  read = &#39;read&#39;,<br>  write = &#39;write&#39;,<br>  publish = &#39;publish&#39;<br>}<br><br>export type TPermission = &#39;read&#39; | &#39;write&#39; | &#39;publish&#39;;<br><br>export type TPrivileges = {<br>  [key in Features]: TPermissions[];<br>}<br><br>export interface IUser {<br>  username: string;<br>  isAuthenticated: boolean;<br>  privileges: TPrivileges;<br>}<br><br>export interface IUserContext {<br>  user: IUser;<br>  saveUser: (newUser: IUser) =&gt; void;<br>}</pre><p><strong>Features — </strong>An enum that describes the features that we are going to have in our application.<br><strong>Permissions —</strong>An enum that describes permissions and allows us to use them all over the application instead of strings.<strong><br>TPermission</strong> — A type that describes the permission that a user can have for each of the features.<br><strong>TPrivileges</strong> — A type that describes what are the permissions that a user has for each of the features that we have in our application.<br><strong>IUser — </strong>An interface that describes a user, which contains a username, his privileges, and a boolean property that says whether the user is authenticated or not.<br><strong>IUserContext — </strong>An interface that describes the context, which will be used wherever we need to get details about the user or save a user.</p><p><strong>Mocks:</strong></p><pre>// /mocks/privileges.ts<br><br>import {TPrivileges, Features, Permissions} from &quot;../types&quot;;<br><br>export const PRIVILEGES_MOCKS: Record&lt;Permissions, TPrivileges&gt; = {<br>    [Permissions.read]: {<br>        [Features.FEATURE_A]: [Permissions.read],<br>    },<br>    [Permissions.write]: {<br>        [Features.FEATURE_A]: [Permissions.read, Permissions.write],<br>    },<br>    [Permissions.publish]: {<br>        [Features.FEATURE_A]: [Permissions.read, Permissions.write, Permissions.publish],<br>    },<br>}</pre><p>A file that we’ll use to simulate the user privileges.</p><p><strong>Context:</strong></p><pre>// /context/user/userContext.tsx<br><br>import React from &#39;react&#39;;<br>import {IUser, IUserContext} from &#39;../../types&#39;;<br><br>const UserContext = React.createContext&lt;IUserContext | undefined&gt;(undefined);<br><br>export default UserContext;</pre><p>Our context is going to store a user object and a saveUser method, which will allow the authentication (login) page to store a new authorized user in the context.</p><p><strong>Provider:</strong></p><pre>// /context/user/userProvider.tsx<br><br>import React, {useState} from &#39;react&#39;;<br>import UserContext from &#39;./userContext&#39;;<br>import {PRIVILEGES_MOCKS} from &#39;../../mocks/privileges&#39;;<br>import {IUser} from &#39;../../types&#39;;<br><br>type TUserProviderProps = {<br>  children: React.ReactNode | React.ReactFragment | React.ReactPortal;<br>}<br><br>export const UserProvider: React.FC&lt;TUserProviderProps&gt; = ({children}) =&gt; {<br>    const [user, setUser] = useState&lt;IUser&gt;({<br>        username: &#39;&#39;,<br>        isAuthenticated: false,<br>        privileges: PRIVILEGES_MOCKS.read<br>    });<br><br>    const saveUser = (newUser: IUser) =&gt; setUser(newUser);<br><br>    return (<br>        &lt;UserContext.Provider value={{ user, saveUser }}&gt;<br>            {children}<br>        &lt;/UserContext.Provider&gt;<br>    );<br>};</pre><p>The provider receives children, which are going to be the component(s) that will be under the UserProvider wrapper and will be able to use or see the user data.</p><p>It has a user state, which is not authenticated by default, doesn’t have a username, and also has <strong>only read privileges</strong>, and defines a <strong>saveUser</strong> method which saves a received user into the user state.</p><p><strong>User Hook</strong></p><pre>// /hooks/useUser.ts<br>import React from &#39;react&#39;;<br>import UserContext from &#39;../context/user/userContext&#39;;<br><br>export const useUser = () =&gt; {<br>    const context = React.useContext(UserContext);<br><br>    if (context === undefined) {<br>        throw new Error(&#39;useUser must be used within a UserProvider&#39;);<br>    }<br><br>    return context;<br>}</pre><p>Last I defined the <strong>useUser</strong> hook, which is responsible to return the context only if it is defined, because, by default, it is not defined.<br>Using this hook, we will be able to access the context directly on every page.</p><h4>Permissions Context</h4><p>Let’s do a small break.<br>Till now, we already have a user context that works, and a protected route that should prevent our users from navigating to pages that they are not allowed to.</p><p>Next, we will have to define the permissions context, which is responsible to tell us whether the user has permission to see a context that is wrapped by a specific privilege or not.</p><p><strong>Types:</strong></p><p>Add the following interface to your types file</p><pre>// /types/index.ts<br><br>export interface IPermissionCache {<br>    [key: string]: TPermission[];<br>}</pre><p><strong>IPermissionCache — </strong>An interface that describes the permissions cache, we’re going to use it in the permissions provider in order to get the user&#39;s permissions faster after the first time it was fetched.</p><p><strong>Context</strong></p><pre>// /context/permission/permissionContext.tsx<br><br>import React from &#39;react&#39;;<br>import { TPermission, Features } from &#39;../../types&#39;;<br><br>type TPermissionContext = {<br>  isAllowedTo: (<br>    feature: Features,<br>    permission: TPermission<br>  ) =&gt; Promise&lt;TPermission[]&gt;;<br>};<br><br>const defaultBehavior: TPermissionContext = {<br>  isAllowedTo: () =&gt; Promise.resolve([]),<br>};<br><br>const PermissionContext =<br>  React.createContext&lt;TPermissionContext&gt;(defaultBehavior);<br><br>export default PermissionContext;</pre><p>The context is going to expose the <strong>isAllowedTo</strong> method which supposes to check if the user is allowed to view a feature by his permissions.</p><p><strong>Provider:</strong></p><pre>// /context/permission/permissionProvider.tsx<br><br>import React, { useCallback } from &#39;react&#39;;<br>import PermissionContext from &#39;./permissionContext&#39;;<br>import { TPermission, IPermissionCache, Features} from &quot;../../types&quot;;<br><br>type TPermissionProviderProps = {<br>  fetchPermission: (<br>    feature: Features,<br>    permission: TPermission<br>  ) =&gt; Promise&lt;TPermission[]&gt;;<br>  children: React.ReactNode | React.ReactFragment | React.ReactPortal;<br>};<br><br>export const PermissionProvider: React.FC&lt;TPermissionProviderProps&gt; = ({<br>  fetchPermission,<br>  children,<br>}) =&gt; {<br>  const cache: IPermissionCache = {};<br><br>  const isAllowedTo = useCallback(<br>    async (<br>      feature: Features,<br>      permission: TPermission<br>    ): Promise&lt;TPermission[]&gt; =&gt; {<br>      if (Object.keys(cache).includes(feature)) {<br>        return cache[feature];<br>      }<br><br>      const isAllowed = await fetchPermission(feature, permission);<br>      cache[feature] = isAllowed;<br><br>      return isAllowed;<br>    },<br>    []<br>  );<br><br>  return (<br>    &lt;PermissionContext.Provider value={{ isAllowedTo }}&gt;<br>      {children}<br>    &lt;/PermissionContext.Provider&gt;<br>  );<br>};</pre><p>Permissions provider stores the cache using the <strong>IPermissionCache</strong> interface we created 2 steps ago and implements the <strong>isAllowedTo</strong> function to first check if there’s data in the cache, and if not, it uses the <strong>fetchPermission </strong>method to get the user privileges for the selected feature.</p><p><strong>Permission Hook:</strong></p><pre>// /hooks/usePermission.ts<br><br>import { useContext, useState } from &#39;react&#39;;<br>import PermissionContext from &#39;../context/permission/permissionContext&#39;;<br>import { Features } from &#39;../enums&#39;;<br>import { TPermission } from &quot;../types&quot;;<br><br>/**<br> * @description Gets user privileges for a feature whether it should be allowed or not for the user<br> * @param feature Feature name<br> * @param permission Permission type<br> */<br>const usePermission = (<br>  feature: Features,<br>  permission: TPermission<br>): { loading: boolean; allowed: TPermission[] } =&gt; {<br>  const [loading, setLoading] = useState&lt;boolean&gt;(true);<br>  const [allowed, setAllowed] = useState&lt;TPermission[]&gt;([]);<br><br>  const { isAllowedTo } = useContext(PermissionContext);<br><br>  isAllowedTo(feature, permission).then((allowed) =&gt; {<br>    setLoading(false);<br>    setAllowed(allowed);<br>  });<br><br>  return { loading, allowed };<br>};<br><br>export default usePermission;</pre><p>Last is the permission hook which we’ll use in a restricted component that we’re just about to create.</p><p>The hook receives a feature name and permissions and checks if the user is allowed to see or interact with this feature, then returns a boolean (allowed) which is the answer to that question.</p><h4>Restricted Component</h4><p>This is the last component that we have to create before we can combine altogether and see it in action.</p><p><strong>Component props:</strong></p><ol><li>feature — The feature name from the Features enum.</li><li>permission — The permission that a specific part of the feature needs in order to view or interact with it.<br>For example, in FEATURE_A, I have multiple buttons, but one of them is allowed only with <strong>publish </strong>privilege. it means that a user with <strong>write</strong> permission shouldn’t see it, but he should see all the rest of the buttons.</li><li>fallback — A component that we will show when there’s an issue fetching the user privilege for a specific component.</li><li>loadingComponent — A component that we’ll show while fetching the user privilege for a specific component</li><li>children — The actual component that should be shown according to user privileges.</li></ol><pre>// /components/Restricted/restricted.tsx<br><br>import React, {ReactElement} from &#39;react&#39;;<br>import usePermission from &quot;../../hooks/usePermission&quot;;<br>import { TPrivileges, IRestrictedProps, Permissions, Features } from &quot;../../types&quot;;<br><br>import * as style from &#39;./style&#39;;<br><br>/**<br> * @description A wrapper that secures a component that it allowed by permissions<br> * @param feature Feature name<br> * @param permission Requested permission<br> * @param fallback Fallback component that could be in use when there is no match between requested permissions and defined permissions<br> * @param loadingComponent Loader that will be shown in the meantime<br> * @param children Component that should be shown according to user privileges<br> * @constructor<br> */<br>export const Restricted: React.FC&lt;IRestrictedProps&gt; = ({<br>  feature,<br>  permission,<br>  fallback,<br>  loadingComponent,<br>  children,<br>}) =&gt; {<br>  const { loading, allowed } = usePermission(feature, permission);<br><br>  if (loading) {<br>    return &lt;&gt;{loadingComponent}&lt;/&gt;;<br>  }<br><br>  const renderChildren = (isReadOnly: boolean = false): ReactElement =&gt; {<br>    return isReadOnly ? &lt;style.ReadOnly&gt;{children}&lt;/style.ReadOnly&gt; : &lt;&gt;{children}&lt;/&gt;<br>  }<br><br>  if (allowed) {<br>    switch (permission) {<br>      case Permissions.read:<br>        if (<br>          allowed.includes(Permissions.write) ||<br>          allowed.includes(Permissions.publish)<br>        ) {<br>          return renderChildren();<br>        } else if (allowed.includes(Permissions.read)) {<br>          return renderChildren(true);<br>        }<br>        break;<br>      case Permissions.write:<br>        if (<br>          allowed.includes(Permissions.write) ||<br>          allowed.includes(Permissions.publish)<br>        ) {<br>            return renderChildren();<br>        }<br>        break;<br>      case Permissions.publish:<br>        if (allowed.includes(Permissions.publish)) {<br>            return renderChildren();<br>        }<br>        break;<br>    }<br>  }<br><br>  return &lt;&gt;{fallback}&lt;/&gt;;<br>};<br><br>// Implement it the way you want.<br>// you can actually fetch the permissions from a backend service or wherever you want.<br>export const fetchPermissions =<br>  (userRole: TPrivileges | null) =&gt;<br>  async (feature: Features) =&gt; {<br>    if (userRole) {<br>      return userRole[feature];<br>    }<br><br>    return [];<br>  };</pre><p>Style:</p><pre>// /components/Restricted/restricted.style.ts<br><br>import styled from &#39;styled-components&#39;;<br><br>export const ReadOnly = styled.span`<br>  pointer-events: none;<br>`;</pre><p>First, the component checks if the user is allowed to see the content at all by using the <strong>usePermissions</strong> hook.</p><p>if the user is allowed, then it checks which privileges he has for this specific component.</p><p>If the required permission to see this component is just <strong>read</strong>, then it checks if the user has <strong>write or publish</strong> permissions, and if so it just renders it, if not and the user <strong>has only read permission</strong>, it will render the component with a wrapper that won’t let the user interact with it using the ReadOnly component which is styled using styled-components.</p><p>If the required permission to see this component is read, then it checks if the user has <strong>write or publish </strong>permissions, and if so, it renders the component and the same for <strong>publish</strong>.</p><p>If none of those exists, then it renders the fallback component, and the user won’t be able to see the component.</p><p>Next, I’ve defined the <strong>fetchPermissions </strong>method, which is responsible to check if the user has privileges for a specific component and returns the privileges for that component or an empty array (which means he doesn’t have any privileges for the component).</p><h4>Combine altogether</h4><p><strong>Login Page</strong></p><p>To make everything work together, I created a login page, which is responsible to save the logged-in user into the user context that we created before, which will give us the ability to visit the user privileges and display to the screen only the component that he allows to view.</p><p>Style:</p><pre>// /pages/Login/login.style.ts<br><br>import styled from &quot;styled-components&quot;;<br><br>export const Login = styled.main`<br>  height: 100vh;<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>`;<br><br>export const FormField = styled.fieldset`<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  gap: 1rem;<br>  border: none;<br>`;</pre><pre>// /pages/Login/index.tsx<br><br>import React, {useState} from &quot;react&quot;;<br>import {useNavigate} from &quot;react-router-dom&quot;;<br><br>import {useUser} from &quot;../../hooks/useUser&quot;;<br>import {IUser} from &quot;../../context/user/userContext&quot;;<br><br>import {PRIVILEGES_MOCKS} from &quot;../../mocks/privileges&quot;;<br><br>import * as style from &#39;./login.style&#39;;<br><br>interface ICredentials {<br>    username: string;<br>    password: string;<br>}<br><br>const Login: React.FC = () =&gt; {<br>    const navigate = useNavigate();<br>    const {saveUser} = useUser();<br>    const [credentials, setCredentials] = useState&lt;ICredentials&gt;({<br>        username: &#39;&#39;,<br>        password: &#39;&#39;<br>    });<br><br>    const onSubmitForm = (e: React.FormEvent) =&gt; {<br>        const {username, password} = credentials;<br><br>        e.preventDefault();<br><br>        if (username &amp;&amp; password) {<br>            const user: IUser = {<br>                                  username,<br>                                  isAuthenticated: true,<br>                                  privileges: PRIVILEGES_MOCKS.read<br>                                };<br>            switch(username) {<br>                case &#39;write&#39;:<br>                    user.privileges = PRIVILEGES_MOCKS.write;<br>                    break;<br>                case &#39;publish&#39;:<br>                    user.privileges = PRIVILEGES_MOCKS.publish;<br>                    break;<br>            }<br>            saveUser(user);<br>            navigate(&#39;/&#39;);<br>        }<br>    }<br><br>    const onChangeInput = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>        const {name, value} = e.target;<br>        setCredentials(prev =&gt; ({...prev, [name]: value}));<br>    }<br><br>    return (<br>        &lt;style.Login&gt;<br>            &lt;form onSubmit={onSubmitForm}&gt;<br>                &lt;style.FormField&gt;<br>                    &lt;label&gt;Username:&lt;/label&gt;<br>                    &lt;input type={&#39;text&#39;} name={&#39;username&#39;} onChange={onChangeInput} /&gt;<br>                &lt;/style.FormField&gt;<br>                &lt;style.FormField&gt;<br>                    &lt;label&gt;Password:&lt;/label&gt;<br>                    &lt;input type={&#39;password&#39;} name={&#39;password&#39;} onChange={onChangeInput} /&gt;<br>                &lt;/style.FormField&gt;<br>                &lt;button type={&#39;submit&#39;}&gt;Submit&lt;/button&gt;<br>            &lt;/form&gt;<br>        &lt;/style.Login&gt;<br>    )<br>}<br><br>export default Login;</pre><p>In order to set different privileges every time for the user, I created a simple login page, which checks only the username and assigns privileges based on it.</p><p>It uses the mock we created before and based on the user name it assigns the right privileges for the user, then uses <strong>saveUser</strong> method which is related to the <strong>useUser</strong> hook to store the user in the context, and then it navigates the user to the home page, which is a protected route.</p><p><strong>Home page</strong></p><pre>// /pages/Home/index.tsx<br><br>import {FC} from &quot;react&quot;;<br><br>import {PermissionProvider} from &quot;../../context/permission/permissionProvider&quot;;<br>import {fetchPermissions, Restricted} from &quot;../../components/Restricted/restricted&quot;;<br>import {Features, Permissions} from &quot;../../enums&quot;;<br>import {useUser} from &quot;../../hooks/useUser&quot;;<br><br>const Home: FC = () =&gt; {<br>    const {user} = useUser();<br><br>    return (<br>        &lt;PermissionProvider fetchPermission={fetchPermissions(user.privileges)}&gt;<br>            &lt;div className=&quot;App&quot;&gt;<br>                &lt;Restricted feature={Features.FEATURE_A} permission={Permissions.read}&gt;<br>                    &lt;p&gt;<br>                        This text is visible if you have at least read privilege.<br>                    &lt;/p&gt;<br>                &lt;/Restricted&gt;<br>                &lt;Restricted feature={Features.FEATURE_A} permission={Permissions.write}&gt;<br>                    &lt;a<br>                        className=&quot;App-link&quot;<br>                        href=&quot;https://reactjs.org&quot;<br>                        target=&quot;_blank&quot;<br>                        rel=&quot;noopener noreferrer&quot;<br>                    &gt;<br>                        This link is visible only if you have write or publish privileges.<br>                    &lt;/a&gt;<br>                &lt;/Restricted&gt;<br>                &lt;Restricted feature={Features.FEATURE_A} permission={Permissions.publish}&gt;<br>                    &lt;button&gt;This button is visible only if you have publish privileges&lt;/button&gt;<br>                &lt;/Restricted&gt;<br>            &lt;/div&gt;<br>        &lt;/PermissionProvider&gt;<br>    )<br>}<br><br>export default Home;</pre><p>On the home page, I used the permission provider to fetch the user privileges from the user object of the <strong>useUser</strong> hook.</p><p>Then I created 3 different areas which are wrapped by the restricted component we made before, and for each of them, I gave another permission type that is required for the user to view or interact with them.</p><p><strong>Demo</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*P09CzhamooaPKXly.gif" /><figcaption>Demo GIF</figcaption></figure><p>You can also easily clone the <a href="https://github.com/RLeDEV/react-rbac-example">source code</a> and run it.</p><p><strong>Did you like it? Read more articles like this one</strong></p><ul><li><a href="https://raz-levy.medium.com/communicating-between-micro-frontends-using-custom-events-in-react-js-e3dab0571edb">Communicating between Micro Frontends using Custom Events in React.JS</a></li><li><a href="https://raz-levy.medium.com/how-to-upload-files-to-aws-s3-from-the-client-side-using-react-js-and-node-js-660252e61e0">How to upload files to AWS S3 from the client-side using React.JS and Node.JS</a></li><li><a href="https://raz-levy.medium.com/how-to-implement-sessions-using-nodejs-and-mongodb-56266bfd19c3">How to Implement Sessions using NodeJS and MongoDB</a></li><li><a href="https://raz-levy.medium.com/build-a-dynamic-modal-component-for-react-js-8ef32bdf6604">Build a Dynamic Modal Component for React JS</a></li></ul><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a7a6a4dd465" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/use-rbac-to-protect-your-reactjs-app-from-unauthorized-access-typescript-6a7a6a4dd465">Use RBAC to Protect Your ReactJS App from Unauthorized Access 🚫 ✅ (TypeScript)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communicating between Micro Frontends using Custom Events in React.JS]]></title>
            <link>https://raz-levy.medium.com/communicating-between-micro-frontends-using-custom-events-in-react-js-e3dab0571edb?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3dab0571edb</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 13:59:03 GMT</pubDate>
            <atom:updated>2022-11-09T08:34:52.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*XHY7yxqxrlual4UKRp91nw.png" /><figcaption>Micro Frontends Architecture (By Alon Gruss)</figcaption></figure><p>As a part of a series of tutorials about Micro Frontends, in this tutorial, I’m going to explain how to communicate between React.JS MFEs using events.</p><p>I will explain why this is the best solution out there nowadays, and what are the pros and cons of using this methodology as well as display an example of usage.</p><h4>Background:</h4><p>In a micro frontend architecture, there should be a shell application that hosts the internal applications and displays them.</p><p>While using this architecture, means that the shell application is not managing the MFEs and that the MFEs are not sharing their states with the shell application or with any of the other MFEs hosted there, by that I mean that you can’t really use any state management such as Redux, MobX (for React) to manage the global states, because when using micro frontends <strong>we don’t want the applications to be coupled.</strong></p><h4>Solution:</h4><p>As a solution, we’re going to use browser events, and create a shared service that will be used by applications to send the events or register to them.</p><p>This solution is more scalable technique for run-time MFEs. The main idea here is to utilize the browser-inbuilt custom events APIs to publish the events with the data from one MFE, while the other MFE subscribes to the events to get the data. This solution is closest to the event-driven architecture in the microservices world.</p><h4>Pros:</h4><ol><li>One of the most common ways to communicate using eventListeners and <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent">CustomEvent</a></li><li>High setup cost but <strong>very </strong>easy to scale.</li><li>The inbuilt solution in-browser platform.</li><li>Build a generic mechanism that all the MFEs teams can follow.</li><li>Framework agnostic (Means it can be implemented even if each of your MFEs uses a different framework)</li></ol><h4>Cons:</h4><ol><li>Not achievable in the case of mobile MFEs.</li><li>Verbose custom events API.</li></ol><h4>Implementation:</h4><p>In the following example, I’m going to show you how to let each of the MFEs fire a Snackbar event to the shell application, and by doing it this way, we will have to implement that Snackbar only inside the shell application instead of implementing it in each of the MFEs.</p><p>First, we have to create a Window Event service that allow to fire events, subscribe, and unsubscribe to events.</p><pre>export interface <strong><em>ISnackbarEvent</em></strong> {<br>  <strong><em>isOpen</em></strong>: boolean;<br>  <strong><em>message</em></strong>: string;<br>  <strong><em>type</em></strong>: &#39;error&#39; | &#39;success&#39;;<br>}</pre><pre>export enum <strong><em>WindowEvents</em></strong> {<br>  <strong><em>SNACKBAR</em></strong><em> </em>= &#39;snackbar&#39;,<br>}</pre><pre>export const <strong><em>WindowEventService </em></strong>= {<br>  fire: (event: WindowEvents, body?: CustomEventInit): void =&gt; {<br>    const customEvent = new CustomEvent(event, body);<br><br>    <strong><em>window</em></strong>.dispatchEvent(customEvent);<br>  },<br>  subscribe: (event: WindowEvents, listener: EventListener) =&gt; {<br>    <strong><em>window</em></strong>.addEventListener(event, listener);<br>  },<br>  unsubscribe: (event: WindowEvents, listener: EventListener) =&gt; {<br>    <strong><em>window</em></strong>.removeEventListener(event, listener);<br>  },<br>};</pre><p>In the code above you can see how I described the Snackbar Event Interface which uses an isOpen property to know if it should be opened, a message which is a string, and a type that can be an error or success and will display a green or red background according to that.</p><p>I’ve also created a WindowEvents enum which should hold all the available events since we need them for both the application that subscribes to the event, and for the application that fire the event, and added SNACKBAR event into it.</p><p>Then, I created WindowEventService which is responsible for fire, subscribing, and unsubscribing to events.</p><h4>Subscribing to an Event:</h4><p>Now, let&#39;s subscribe to the Snackbar event in the shell application:</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import { Snackbar<strong><em> </em></strong>} from &#39;shared-lib/Snackbar&#39;;<br>import {<br>  WindowEvents,<br>  WindowEventService,<br>  ISnackbarEvent,<br>} from &#39;shared-lib/services&#39;;<br><br>import &#39;./style.scss&#39;;<br><br>const SnackbarDefaultValue: ISnackbarEvent = {<br>  isOpen: false,<br>  message: &#39;&#39;,<br>  type: &#39;success&#39;,<br>};<br><br>export function App() {<br>  const [snackbar, setSnackbar] =<br>    useState&lt;ISnackbarEvent&gt;(SnackbarDefaultValue);<br><br>  useEffect(() =&gt; {<br>    <strong><em>WindowEventService</em></strong>.subscribe(WindowEvents.<em>SNACKBAR</em>, updateSnackbar);<br><br>    return () =&gt; {<br>      <strong><em>WindowEventService</em></strong>.unsubscribe(WindowEvents.<em>SNACKBAR</em>, updateSnackbar);<br>    };<br>  }, [updateSnackbar]);</pre><pre>  const updateSnackbar = (event: Event) =&gt; {<br>    const { detail } = event as CustomEvent&lt;ISnackbarEvent&gt;;<br>    setSnackbar({ ...snackbar, ...detail });<br>  };</pre><pre>  const onCloseSnackbar = () =&gt; {<br>    setSnackbar({ ...snackbar, isOpen: false, message: &#39;&#39; });<br>  };<br><br>  return (<br>      &lt;div className=&quot;app-container&quot;&gt;<br>        &lt;div className=&quot;snackbar-container&quot;&gt;<br>          &lt;Snackbar<br>            content={snackbar.message}<br>            type={snackbar.type}<br>            isOpen={snackbar.isOpen}<br>            onClose={onCloseSnackbar}<br>          /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In the shell application, I used the <strong>subscribe</strong> function to subscribe to the snackbar event, and passed the updateSnackbar function which will be responsible to get the event from the service and handle it.</p><p>I’ve also cleaned the subscription on unmount using the <strong>unsubscribe</strong> function.</p><h4>Firing an Event:</h4><pre>import React from &#39;react&#39;;<br>import { ISnackbarEvent, WindowEvents, WindowEventService } from &#39;shared-libs/services&#39;;<br><br>import &#39;./index.scss&#39;;<br><br>const App = () =&gt; {<br>  const triggerSnackbar = () =&gt; {<br>    <strong><em>WindowEventService</em></strong>.fire(WindowEvents.<em>SNACKBAR</em>, { detail: {<br>  isOpen: true,<br>  message: &#39;Operation succeed&#39;,<br>  type: &#39;success&#39;,<br>    }});<br>  };<br><br>  return (<br>    &lt;div className=&quot;app-container&quot;&gt;<br>      &lt;button onClick={fireSuccessSnackbar}&gt;<br>        Fire Snackbar<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>In the following code, you can see that all we have to do to fire an event is to send the event data inside the detail object, and then, if the shell application (or any other application) subscribed to that SNACKBAR event, they will receive the data.</p><p><strong>That&#39;s it, your micro frontends now can communicate with each other, they don’t even have to know them, and they are still loosely coupled.</strong></p><p>If you want to learn more, lookup for my previous articles:</p><ul><li><a href="https://raz-levy.medium.com/upload-images-to-aws-s3-using-react-js-and-node-js-express-server-bc15b959372c">How to upload images to AWS S3 using React.JS and Node.JS express server</a></li><li><a href="https://aws.plainenglish.io/white-listing-ips-to-your-website-environments-using-aws-waf-551230cbb07c">How to White-list IPs to Website Environments Using AWS Web Application Firewall</a></li><li><a href="https://raz-levy.medium.com/build-a-dynamic-modal-component-for-react-js-8ef32bdf6604">Build a Dynamic Modal Component for React JS</a></li><li><a href="https://aws.plainenglish.io/deploy-react-app-to-aws-s3-static-website-host-8f5cf688f3ad">How to Deploy React App to AWS S3 Static Website Host</a></li><li><a href="https://raz-levy.medium.com/how-to-upload-files-to-aws-s3-from-the-client-side-using-react-js-and-node-js-660252e61e0">How to upload files to AWS S3 from the client-side using React.JS and Node.JS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3dab0571edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Sessions using NodeJS and MongoDB]]></title>
            <link>https://raz-levy.medium.com/how-to-implement-sessions-using-nodejs-and-mongodb-56266bfd19c3?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/56266bfd19c3</guid>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[express-session]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[express]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 12:30:50 GMT</pubDate>
            <atom:updated>2022-07-02T12:30:50.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RiJviwFAo_3TWYI-Ayiow.jpeg" /></figure><p>When I started learning about sessions and their meaning it wasn’t easy to understand what is the correct flow and how things should be configured to make sessions work.</p><p>As a Full Stack Developer at <a href="https://medium.com/u/bcab3a3ded39">Joonko</a>, we had to start working on a new version of the company’s product and we had to implement an ability for users to sign in to the system and do some actions, and for that, we had to implement sessions in our backend server.</p><h3>How do sessions work?</h3><p>When a user logs in to a system and makes a login request to the server, the server will create a session and store it on the server’s local cache or in external storage (database).<br>Then, after finishing this process, the server responds to the client with a cookie.<br>The cookie usually contains a unique ID which is the <strong>session id</strong> and will be stored on the client browser for a limited time.<br>From this point, every request that will be sent to the server will include the browser cookies including the session cookie.</p><h3>About express-session:</h3><p><a href="https://www.npmjs.com/package/express-session">express-session</a> is an HTTP server-side framework that can be used to create and manage a session middleware, this package will be our main thing for this tutorial.</p><h3>Set up a project:</h3><p>Use the following command to initialize a NodeJS project:</p><pre>npm init -y</pre><p>Next, use the following command to install express and express-session:</p><pre>npm install express express-session connect-mongo</pre><p>Next, create a new file named <strong>app.js </strong>and add the following code to it:</p><pre>const express<strong><em> </em></strong>= require(&#39;express&#39;);<br>const session = require(&#39;express-session&#39;);<br>const MongoStore = require(&#39;connect-mongo&#39;);<br><br>const app = express();<br><br>app.use(session({<br>    name: &#39;example.sid&#39;,<br>    secret: &#39;Replace with your secret key&#39;,<br>    httpOnly: true,<br>    secure: true,<br>    maxAge: 1000 * 60 * 60 * 7,<br>    resave: false,<br>    saveUninitialized: true,<br>    store: MongoStore.<em>create</em>({<br>        mongoUrl: &#39;MongoDB URL should be here&#39;<br>    })<br>}));<br><br>app.listen(4000, () =&gt; {<br>    console.log(&quot;App listening on port 4000&quot;)<br>})</pre><p><strong>Explanation:</strong></p><ol><li>We’ve created a new instance of express server and initialized a variable called app with it.</li><li>Next, we’ve added a session middleware to the application server with the following configuration:<br>- <strong>name:</strong> The name of the cookie that will be stored on the client-side.<br>- <strong>secret:</strong> This is the secret used to sign the ID cookie.<br>- <strong>httpOnly</strong>: Specifies the value of httpOnly Set-Cookie attribute.<br>- <strong>secure: </strong>Specifies the value of secure Set-Cookie (note that this one will work only if you are using HTTPS on your environment).<br>- <strong>maxAge: </strong>Specifies the cookie’s max-age in milliseconds, I’ve already set it to 7 hours.<br>- <strong>resave:</strong> Forces the session to be saved back to the session store.<br>-<strong> saveUnitialized:</strong> Forces a session that is “uninitialized” to be saved to the session store.<br>- <strong>store:</strong> Uses MongoDB store which was implemented by connect-mongo NPM library and which you can view <a href="https://www.npmjs.com/package/connect-mongo"><strong>here</strong></a> and describes the connection between it.</li><li>Initializing a server and listening to port 4000.</li></ol><p>Next, all we have to do is to implement a few routes that will use the middleware we created above.</p><p>In the following examples, I’ll create <strong>very simple routes</strong> just so you can understand better the usage of this middleware.</p><h3><strong>&lt;POST&gt; Create User Route</strong></h3><pre>app.post(&#39;/&#39;, async (req, res, next) =&gt; {<br>    const {name} = req.body;<br>    req.session.user = {<br>        name,<br>        isLoggedIn: true<br>    }<br><br>    try {<br>        await req.session.save();<br>    } catch (err) {<br>        <strong><em>console</em></strong>.error(&#39;Error saving to session storage: &#39;, err);<br>        return next(new Error(&#39;Error creating user&#39;));<br>    }<br><br>    res.status(200).send();<br>})</pre><p>The following route handles a POST request with a name in the request’s body, it enriches the request session’s user data and saves the updated session into the MongoDB sessions collection using the <strong>req.session.save</strong> method.</p><h3>&lt;POST&gt; Logout User Route</h3><pre>app.post(&#39;/logout&#39;, async (req, res, next) =&gt; {<br>    try {<br>        await req.session.destroy();<br>    } catch (err) {<br>        <strong><em>console</em></strong>.error(&#39;Error logging out:&#39;, err);<br>        return next(new Error(&#39;Error logging out&#39;));<br>    }<br>    <br>    res.status(200).send();<br>})</pre><p>The following route handles a POST request and everything it does is to destroy the current user’s session — which means that it will remove the session from the MongoDB sessions collection as well as delete the session cookie from the user’s browser.</p><h3>&lt;GET&gt; User Full Name Route</h3><pre>app.get(&#39;/name&#39;, (req, res) =&gt; {<br>    let name;<br><br>    if (!req.session) {<br>        return res.status(404).send();<br>    }<br><br>    name = req.session.user.name;<br><br>    return res.status(200).send({name});<br>})</pre><p>The following route handles GET request and return the full name of a user from his session data if it exists.</p><p><strong>If you followed all the steps and did it all correctly, then it means that you will be able to access req.session object which will include everything you included in it the last time you used the save method.</strong></p><p>If you want to learn more, lookup for my previous articles:</p><ul><li><a href="https://raz-levy.medium.com/upload-images-to-aws-s3-using-react-js-and-node-js-express-server-bc15b959372c">How to upload images to AWS S3 using React.JS and Node.JS express server</a></li><li><a href="https://raz-levy.medium.com/build-a-dynamic-modal-component-for-react-js-8ef32bdf6604">Build a Dynamic Modal Component for React JS</a></li><li><a href="https://aws.plainenglish.io/white-listing-ips-to-your-website-environments-using-aws-waf-551230cbb07c">How to White-list IPs to Website Environments Using AWS Web Application Firewall</a></li><li><a href="https://aws.plainenglish.io/deploy-react-app-to-aws-s3-static-website-host-8f5cf688f3ad">How to Deploy React App to AWS S3 Static Website Host</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56266bfd19c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to upload files to AWS S3 from the client-side using React.JS and Node.JS]]></title>
            <link>https://raz-levy.medium.com/how-to-upload-files-to-aws-s3-from-the-client-side-using-react-js-and-node-js-660252e61e0?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/660252e61e0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Wed, 22 Jun 2022 14:20:53 GMT</pubDate>
            <atom:updated>2022-06-22T14:20:53.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*3uCSHoUxe5YMYBxK.jpeg" /></figure><p>Since I published my last tutorial on <a href="https://raz-levy.medium.com/upload-images-to-aws-s3-using-react-js-and-node-js-express-server-bc15b959372c">How to upload images to AWS S3 using React.JS and Node.JS express server</a> many individuals kept on asking me if there’s an option to upload the image on the client-side and avoid sending the whole file object to the server-side.</p><h4><strong>The answer is YES!</strong></h4><p>In this tutorial, I’ll explain the difference between using both technics and I’ll explain how to upload a file from the client-side to AWS S3 using React.JS on the frontend and Node.JS express server on the backend, <strong>but this time, the upload process will take place in the frontend platform.</strong></p><h3>Prerequisites:</h3><ul><li><a href="https://nodejs.org/en/download/">NodeJS</a> installed.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html">AWS CLI V2</a> installed and configured to your AWS account.</li><li>AWS S3 bucket with public access permissions.</li><li><a href="https://github.com/RLeDEV/node-express-boilerplate">Empty NodeJS project (you can use a boilerplate I made)</a></li></ul><h3>Client-side VS Server-side uploading differences:</h3><p>So actually there are a few differences when choosing how to upload a file, following are some of them:</p><ol><li>Uploading a file from the<strong> client-side</strong> means that the action is done on the user’s device, while the <strong>server-side</strong> means that the action takes place on the webserver.</li><li>When uploading a large file to AWS S3 it might be better to upload it from the client-side because sending it to the server-side and processing the file can be very heavy for the bandwidth among other considerations such as <strong>cost, </strong>while inbound traffic to the server is free, the outbound from the server will accrue charges, in addition, when thinking about <strong>performance</strong>, it will depend on type and size of the chosen server instance.</li><li>On the other hand, when uploading a file from the client side there are other challenges such as <strong>security </strong>which means that when you provide the ability to upload a file from the client side you should do it by using signed URLs, and the <strong>performance</strong> will be limited to the performance of the user’s internet connection.</li><li>When you choose to go with the client-side solution, you will have the ability to use a serverless function to generate a signed URL instead of having a live server that will have to handle the upload request, the main reason you won’t be able to go serverless if you choose to go with the server-side solution is that AWS API Gateway has a limitation of 5MB per request, which means it will be much harder to process a request with a file and that you’ll have to stream it.</li></ol><h3>Open CORs and permissions on S3 Bucket:</h3><ol><li>Enter your S3 bucket and navigate to <strong>permissions</strong> on the top navigation bar.</li><li>Scroll down until you see <strong>Bucket Policy,</strong> click on edit and enter the following permissions (replace &lt;bucket_name&gt; with your bucket name:</li></ol><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;PublicRead&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:PutObject&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;bucket_name&gt;/*&quot;<br>        }<br>    ]<br>}</pre><p>3. Scroll down to <strong>CORS</strong>, click on edit and add the following:</p><pre>[<br>    {<br>        &quot;AllowedHeaders&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;AllowedMethods&quot;: [<br>            &quot;GET&quot;,<br>            &quot;PUT&quot;,<br>        ],<br>        &quot;AllowedOrigins&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;ExposeHeaders&quot;: []<br>    }<br>]</pre><h3>Generating a signed URL:</h3><p>Alright, so once you chose to go with the client-side solution, all you will have to do on your backend side is to generate a signed URL using the <a href="https://www.npmjs.com/package/aws-sdk">aws-sdk</a> npm package.</p><p>First, in case you haven’t downloaded yet my boilerplate for Node.JS you can do it by cloning the following <a href="https://nodejs.org/en/download/">repository</a>.</p><p>Next, we have to install the aws-sdk npm library by entering the following in the terminal:</p><pre>npm install --save aws-sdk</pre><h4>Define a service:</h4><p>Next, open a new directory under the <strong>src</strong> folder and call it <strong>services</strong>, in this folder you can place all the services you’ll use in the application.<br>In the services directory, open a new file and call it <strong>filesService.js, </strong>this file will contain all the code you need to make a new signed URL.</p><p>In the file enter the following code:</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const BUCKET_NAME = process.env.BUCKET_NAME;<br>const s3 = new AWS.S3({signatureVersion: &#39;v4&#39;});<br><br><em>/**<br> * </em><strong><em>@description </em></strong><em>Generated a signed and a public urls for a given file name<br> * </em><strong><em>@param </em></strong><em>filename File name including file extension<br> * </em><strong><em>@param </em></strong><em>bucketPath Folder path in S3<br> * </em><strong><em>@returns </em></strong><em>{publicUrl: string, signedUrl: string}<br> */<br></em>const generateUrl = async (filename, bucketPath) =&gt; {<br>    let signedUrl;<br>    const publicUrl = getPublicUrl(filename, bucketPath);<br>    const params = {<br>        Bucket: BUCKET_NAME,<br>        Key: `${bucketPath}/${filename}`,<br>        Expires: 60,<br>        ACL: &#39;public-read&#39;<br>    }<br><br>    try {<br>        signedUrl = await s3.getSignedUrlPromise(&#39;putObject&#39;, params);<br>    } catch (err) {<br>        <strong><em>console</em></strong>.error(`Error generating pre-signed url: ${err.message}`);<br>        throw new Error(&#39;Error generating pre-singed url&#39;);<br>    }<br><br>    return {signedUrl, publicUrl};<br>}<br><br><em>/**<br> * </em><strong><em>@description </em></strong><em>generates a public URL<br> * </em><strong><em>@param </em></strong><em>filename File name including file extension<br> * </em><strong><em>@param </em></strong><em>bucketPath Folder path to file<br> * </em><strong><em>@returns </em></strong><em>{string}<br> */<br></em>const getPublicUrl = (filename, bucketPath) =&gt; {<br>    const publicUrl = `https://s3.amazonaws.com/${BUCKET_NAME}/${bucketPath}/${filename}`<br><br>    return publicUrl;<br>}<br><br>module.exports = {generateUrl};</pre><p><strong>Explanation:</strong></p><ol><li>I’ve initialized new AWS and S3 instances.</li><li>I’ve declared a constant called BUCKET_NAME with takes the bucket name from the BUCKET_NAME environment variable.</li><li>I’ve defined a function called generateUrl which receives a filename, which is a string of the filename that you want to store in S3, and bucketPath which is a string that describes the folders tree to the file in S3.<br>In that function, I’ve defined a constant with the name params which describes the parameters for S3.getSignedUrlPromise function and include the bucket name, the key for the requested file, the amount of time that the URL will be valid in seconds (expires), and the access control list (ACL).</li><li>Another function I’ve defined is getPublicUrl which was in use in the last function and receives a filename and bucketPath, both are strings and return a public URL to the requested file.</li></ol><h4>Define a route:</h4><p>The next step is to create a route that will handle the requests and will create the signed URL.<br>For that, create a new file under src/routes folder and call it <strong>files.js, </strong>and enter the following code into it:</p><pre>const <strong><em>express </em></strong>= require(&#39;express&#39;);<br>const <strong><em>router </em></strong>= <strong><em>express</em></strong>.Router();<br>const <strong><em>filesService </em></strong>= require(&#39;../services/filesService&#39;);<br><br><strong><em>router</em></strong>.get(&#39;/&#39;, async (req, res) =&gt; {<br>    const {filename, path} = req.query;<br>    const urls = await <strong><em>filesService</em></strong>.generateUrl(filename, path);<br><br>    res.send({urls});<br>})<br><br>module.exports = <strong><em>router</em></strong>;</pre><p><strong>Explanation:</strong></p><ol><li>I’ve initialized a new route that will handle the routes declarations with the name <strong>router</strong>.</li><li>I’ve imported the early created files service.</li><li>I’ve defined a new GET route to the ‘/’ endpoint, exported filename and path from the request’s query, generated the signed and public URLs using the imported files service from the last step, and returned it to the client.</li></ol><p>Next, all we have to do is to add the newly created route to our routes map, to do so, enter src/routes/index.js file, import the newly created router into it add a new endpoint called ‘files’ and bind that router into it.</p><pre>const <strong><em>express </em></strong>= require(&#39;express&#39;);<br>const <strong><em>router </em></strong>= <strong><em>express</em></strong>.Router();<br><br>const <strong><em>files </em></strong>= require(&#39;./files&#39;);<br><br><strong><em>router</em></strong>.use(&#39;/files&#39;, <strong><em>files</em></strong>);<br><br>module.exports = <strong><em>router</em></strong>;</pre><p>Now it’s we’re ready on the server-side.</p><h3>Handling the client-side:</h3><p>Now, after we’ve already finished with the server-side, we have to handle the client-side requests and processes.</p><p>For this, create a new react application using the CRA and enter it:</p><pre>npx create-react-app signed_url_demo</pre><p>Once it’s done initializing your application, enter the terminal and install the axios npm package, which will help us to handle HTTP requests:</p><pre>npm install --save axios </pre><p>Next, we have to display a file input field on the main page.<br>For that, enter <strong>app.js</strong> file and replace the HTML with the following:</p><pre>&lt;div className=&quot;header&quot;&gt;<br>    &lt;input type=&quot;file&quot; id=&quot;file_input&quot;/&gt;<br>&lt;/div&gt;</pre><p>Next, we’ll have to handle the changes on this input.<br>To do so, let’s create a new function called onFileInput which will handle the onChange functionality of the input:</p><pre>const onFileInput = async (e) =&gt; {<br>    const timestamp = new <strong><em>Date</em></strong>().getTime();<br>    const file = e.target.files[0];<br>    const filename = file.name.split(&#39;.&#39;)[0].replace(/[&amp;<strong>\/</strong>\\#,+()$~%&#39;&quot;:*?&lt;&gt;{}]/g, &#39;&#39;).toLowerCase() + `_${timestamp}`;<br>    const fileExtension = file.name.split(&#39;.&#39;).pop();<br><br>    await uploadImage(`${filename}.${fileExtension}`, file);<br>}</pre><p><strong>Explanation:</strong></p><ol><li>I want to make a unique file name every time and to prevent overriding an existing file on S3, for this I’ve defined a variable called timestamp that hold the current timestamp and will be concatenated to the file name.</li><li>I’ve initialized a new variable called file which holds the chosen file.</li><li>I’ve initialized a new variable called filename which holds the name of the file <strong>without </strong>its extension (pdf, png, csv, jpg, etc..) and I removed the special characters from it if any.</li><li>Next, I’ve initialized another variable called fileExtension to hold the extension of the file.</li><li>The last thing is to call another function that will actually hold the image uploading called uploadImage which receives the new filename (with timestamp) and the actual file.</li></ol><p>Now, after we created that function, we have to define the <strong>uploadImage</strong> function which is actually going to upload the function and use the backend server we created earlier.<br>For this, I’ve created it at the top of the App.js declaration a new state called imageUrl which is going to hold the public URL of the file, and initialized it to null since we don’t have an image URL when the page is rendered.</p><p>Add the following to your code:</p><pre>const [imageUrl, setImageUrl] = useState(null);</pre><p><strong>uploadImage:</strong></p><pre>const uploadImage = async (filename, file) =&gt; {<br>    const foldersPath = &#39;tests/test1&#39;;<br>    const options = { headers: { &#39;Content-Type&#39;: file.type } };<br><br>    try {<br>        const s3Urls = await <strong><em>axios</em></strong>.get(<br>            `http://localhost:3001/api/v1/files?filename=${filename}&amp;path=${foldersPath}&amp;contentType=${file.type}`<br>        ).then(response =&gt; response.data?.urls);<br><br>        if (!s3Urls.signedUrl) {<br>            throw new Error(&#39;S3 signed url is not defined&#39;);<br>        }<br><br>        await <strong><em>axios</em></strong>.put(s3Urls.signedUrl, file, options);<br><br>        setImageUrl(s3Urls.publicUrl);<br>    } catch (err) {<br>        <strong><em>console</em></strong>.error(`Error uploading image: ${err.message}`);<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ol><li>I’ve defined a new variable called foldersPath which holds the requested folders tree to the file on S3.</li><li>I’ve defined a new variable called options which holds the header ContentType with the type of the chosen file.</li><li>Next, I’ve used axios to send a request to our API with the filename and the requested path and stored the response in s3Urls variable.</li><li>Now,<strong> it’s a very important part</strong>, I’ve used the returned signedUrl from our backend server and sent a PUT request to it with the chosen file and the options variable.</li><li>Next, I’ve set the publicUrl to imageUrl state we’ve defined above.</li></ol><p>Next, all we have to do is to place the onFileInput function to receive the events on the onChange for the input field and to display the imageUrl when it’s available under the input field, for that, replace the HTML on your app with the following.</p><pre>&lt;div className=&quot;header&quot;&gt;<br>    &lt;input type=&quot;file&quot; id=&quot;file_input&quot; onChange={onFileInput} /&gt;<br>    {imageUrl &amp;&amp; &lt;div className=&quot;result&quot;&gt;<br>        &lt;a href={imageUrl} className=&quot;image-url&quot; target=&quot;_blankד&quot;&gt;Uploaded Image&lt;/a&gt;<br>    &lt;/div&gt;<br>    }<br>&lt;/div&gt;</pre><p>Now, run both your backend server and your React application, and everything should work like a charm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*TgpuZyvMhLmOQWoPhu5GjA.gif" /><figcaption>Result image</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=660252e61e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to upload images to AWS S3 using React.JS and Node.JS express server]]></title>
            <link>https://raz-levy.medium.com/upload-images-to-aws-s3-using-react-js-and-node-js-express-server-bc15b959372c?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc15b959372c</guid>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 16:13:18 GMT</pubDate>
            <atom:updated>2021-12-27T18:02:49.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*AN30FdjlH5ra06VUT4Sdjg@2x.jpeg" /><figcaption>Image by Joonko</figcaption></figure><p>One of the more difficult things for me when I started messing with AWS was to learning all the different ways to upload a file to an S3 bucket, and then determine the best realize in my situation (uploading directly from the Frontend or whether doing it involving a Backend server).</p><p>As a Full Stack developer at <a href="https://medium.com/u/bcab3a3ded39">Joonko</a>, we had a few different places in our application where we wanted to let the user the ability to upload an image, and for this, we chose to do it by forwarding the image from the frontend (ReactJS) to the backend server (NodeJS) using Base64 format and upload it from there directly to S3.</p><h4>How did we do it?</h4><p>Since our API did not support file uploading, we chose to convert the image that the user uploaded on the frontend to a <a href="https://en.wikipedia.org/wiki/Base64">base64</a> string and to pass it to the server using the request body. The server received the request, decoded the passed base64 string, and uploaded the original resource to S3 using the popular <a href="https://www.npmjs.com/package/aws-sdk">aws-sdk npm library</a>.</p><p>In this tutorial, I’ll guide you on how to convert an image object on a frontend project built with ReactJS to base64, pass it to your server using an HTTP request (POST), and how to create a service on your backend server built with NodeJS specifically for uploading images to S3.</p><h4>Prerequisites:</h4><ul><li><a href="https://nodejs.org/en/download/">NodeJS</a> installed.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html">AWS CLI v2</a> installed and configured with your AWS account.</li><li>AWS S3 bucket with public access permissions.</li></ul><h4>~ Create React application ~</h4><p>Alright, so first, we will need to create a new React application.<br>Get into your terminal and use to the following command to create a new application:</p><pre>npx create-react-app upload_image_to_s3</pre><p>Now, open the newly created project on your favorite IDE, and let’s add some functionality to enable the user the ability to choose an image from his local machine:</p><h4>~ Add the ability to upload an image ~</h4><p>In the <strong>src </strong>directory, add a new file called <strong>uploadImage.js</strong>, and add the following code into it:</p><pre>import React from &#39;react&#39;;</pre><pre>const UploadImages = () =&gt; {<br>    return (<br>        &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; /&gt;<br>    )<br>}</pre><pre>export default UploadImages;</pre><p>The code above simply implements an input element that accepts only image files.<br>Now, import this component in your App.js, and the following input element should be rendered in your application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*fHN5ED-KMCj1T5v8f62irg.png" /><figcaption>Choose image input rendered</figcaption></figure><p>Next, we need to create a function to handle the onChange event on the input we created above, and a function that will convert the selected file into base64:</p><pre>import React from &#39;react&#39;;</pre><pre>const UploadImages = () =&gt; {<br>    const onSelectFile = async (event) =&gt; {<br>        const file = event.target.files[0];<br>        const convertedFile = await convertToBase64(file);<br>        <br>        // Request will be sent from here in the future<br>    }</pre><pre>    const convertToBase64 = (file) =&gt; {<br>        return new Promise(resolve =&gt; {<br>            const reader = new FileReader();</pre><pre>            reader.readAsDataURL(file);<br>            reader.onload = () =&gt; {<br>                resolve(reader.result);<br>            }<br>        })<br>    }</pre><pre>    return (<br>        &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; onChange={onSelectFile}/&gt;<br>    )<br>}</pre><pre>export default UploadImages;</pre><p><strong>convertToBase64</strong> function will convert our file into base64 using a the readAsDataUrl function of FileReader.<br><strong>onSelectFile</strong> function will handle the onChange event for the input element, note that I’ve added the function to the onChange property of the input element as well.</p><p>Next, we will use Axios to send an asynchronous POST request to the server (which is not ready yet) and send our just created base64 string in its body.</p><p>So, first, install <a href="https://www.npmjs.com/package/axios">Axios</a> using the following command:</p><pre>npm install --save axios</pre><p>Next, let’s import Axios at the top of the file and modify the <strong>onSelectFile</strong> function to send the POST request:</p><pre>const onSelectFile = async (event) =&gt; {<br>    const file = event.target.files[0];<br>    const convertedFile = await convertToBase64(file);</pre><pre>    const s3URL = await axios.post(<br>        &#39;http://localhost:3001/upload&#39;,<br>        {<br>            image: convertedFile,<br>            imageName: file.name<br>        }<br>    );<br>}</pre><p>I’ve also defined the <strong>s3URL</strong> variable so in the future we will also be able to display the image on the frontend.</p><p>Everything is ready on the frontend side, now, let’s move to the <strong>backend</strong> side of our project.</p><h4>~ Create a simple Express server ~</h4><p>You can simply create an Express server or easier clone a boilerplate I made for the NodeJS-Express server using the following <a href="https://github.com/RLeDEV/node-express-boilerplate">GitHub repository</a>.</p><p>In this section, I’ll cover the option using my own boilerplate which I just mentioned.</p><p>Get into the cloned directory and enter the following command into your terminal to install the project’s dependencies:</p><pre>npm install</pre><p>Next, get into src/routes and rename example.js to upload.js .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GYGFtAMGQskaEiHS" /><figcaption>Photo by <a href="https://unsplash.com/@douglasamarelo?utm_source=medium&amp;utm_medium=referral">Douglas Lopes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>~ Create image upload service ~</strong></h4><p>In this section, we’re going to create a simple images upload to AWS S3.<br>First, we need to install the aws-sdk, enter the following command:</p><pre>npm install --save aws-sdk</pre><p>Next, add a new environment variable called <strong>IMAGES_BUCKET </strong>with the name of your S3 bucket, navigate to src/services and create a new file called imagesService.js and enter the following code into it:</p><pre>const AWS = require<em>(</em>&#39;aws-sdk&#39;<em>)</em>;<br>const BUCKET_NAME = <strong><em>process</em></strong>.env.IMAGES_BUCKET;<br>const s3 = new AWS.S3<em>({})</em>;<br><br><em>/**<br> * </em><strong><em>@description </em></strong><em>Uploads an image to S3<br> * </em><strong><em>@param </em></strong><em>imageName Image name<br> * </em><strong><em>@param </em></strong><em>base64Image Image body converted to base 64<br> * </em><strong><em>@param </em></strong><em>type Image type<br> * </em><strong><em>@return </em></strong><em>string S3 image URL or error accordingly<br> */<br></em>async function upload<em>(</em>imageName, base64Image, type<em>) <br></em>    const params = {<em><br>        </em>Bucket: `$<em>{</em>BUCKET_NAME<em>}</em>/images`,<br>        Key: imageName,<br>        Body: new <strong><em>Buffer</em></strong>.from<em>(</em>base64Image.replace<em>(</em>/^data:image<strong>\/</strong>\w+;base64,/, &quot;&quot;<em>)</em>, &#39;base64&#39;<em>)</em>,<br>        ContentType: type<br>    <em>}</em>;<br><br>    let data;<br><br>    try <em>{<br>        </em>data = await promiseUpload<em>(</em>params<em>)</em>;<br>    <em>} </em>catch <em>(</em>err<em>) {<br>        </em><strong><em>console</em></strong>.error<em>(</em>err<em>)</em>;<br><br>        return &quot;&quot;;<br>    <em>}<br><br>    </em>return data.Location;<br><em>}</em></pre><pre><em>/**<br> * </em><strong><em>@description </em></strong><em>Promise an upload to S3<br> * </em><strong><em>@param </em></strong><em>params S3 bucket params<br> * </em><strong><em>@return </em></strong><em>data/err S3 response object<br> */<br></em>function promiseUpload<em>(</em>params<em>) {<br>    </em>return new <strong><em>Promise</em></strong><em>(</em>function <em>(</em>resolve, reject<em>) {<br>        </em>s3.upload<em>(</em>params, function <em>(</em>err, data<em>) {<br>            </em>if <em>(</em>err<em>) {<br>                </em>reject<em>(</em>err<em>)</em>;<br>            <em>} </em>else <em>{<br>                </em>resolve<em>(</em>data<em>)</em>;<br>            <em>}<br>        })</em>;<br>    <em>})</em>;<br><em>}<br><br></em>module.exports = <em>{</em>upload<em>}</em>;</pre><p>There are 2 functions above, the first one is the handler that will receive the data from the route that we will build in the next section.<br>The <strong>upload </strong>function simple receives the imageName, the body converted to base64 and the file type (jpg/png/svg/etc..), and build an object called params that will be passed to the <strong>promiseUpload</strong> function which is responsible to upload the file to S3 using the received params.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EWQx5BrLl74MIXIc" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>~ Create upload route ~</h4><p>Navigate to src/routes and rename example.js to upload.js , remove the router.getfunction and add the following code instead:</p><pre><strong><em>router</em></strong>.post<em>(</em>&#39;/images&#39;, validateImageType, validateImageExtension, validateImageObject, validate, async <em>(</em>req, res, next<em>) </em>=&gt;<em><br></em>    const base64Image = req.body.image;<br>    const imageName = req.body.name;<br>    const type = req.body.type;</pre><pre>    let response;<br><br>    try <em>{<br>        </em>response = await <strong><em>imagesService</em></strong>.upload<em>(</em>imageName, base64Image<em>)</em>;<br>    <em>} </em>catch <em>(</em>err<em>) {<br>        </em><strong><em>console</em></strong>.error<em>(</em>`Error uploading image: ${err.message}`<em>)</em>;<br>        return next<em>(</em>new <strong><em>Error</em></strong><em>(</em>`Error uploading image: $<em>{</em>imageName<em>}</em>`<em>))</em>;<br>    <em>}<br><br>    </em>res.send<em>({</em>link: response<em>})</em>;<br><em>})</em></pre><p>The following route is a POST route that should receive the following body:</p><ul><li>image: The converted to base64 string.</li><li>imageName: The image’s source name.</li><li>type: The image’s type (image/jpeg, image/xml+svg, etc..)</li></ul><p>and should use the imagesService we built earlier to upload it to S3, and return the new s3 generated link to the user.</p><p><strong>Now, if you followed all the steps up there correctly, all you have to do is to run both, your ReactJS project and your NodeJS project and choose a file.</strong></p><p>If you want to learn more, lookup for my previous articles:</p><ul><li><a href="https://raz-levy.medium.com/build-a-dynamic-modal-component-for-react-js-8ef32bdf6604">Build a Dynamic Modal Component for React JS</a></li><li><a href="https://aws.plainenglish.io/white-listing-ips-to-your-website-environments-using-aws-waf-551230cbb07c">How to White-list IPs to Website Environments Using AWS Web Application Firewall</a></li><li><a href="https://aws.plainenglish.io/deploy-react-app-to-aws-s3-static-website-host-8f5cf688f3ad">How to Deploy React App to AWS S3 Static Website Host</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc15b959372c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Dynamic Modal Component for React JS]]></title>
            <link>https://raz-levy.medium.com/build-a-dynamic-modal-component-for-react-js-8ef32bdf6604?source=rss-384c08383c4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ef32bdf6604</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[scratch-programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[modal]]></category>
            <dc:creator><![CDATA[Raz Levy]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 18:55:51 GMT</pubDate>
            <atom:updated>2021-11-11T18:55:51.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8xlUcNmGUUd4esoQ" /><figcaption>Photo by <a href="https://unsplash.com/@creativechristians?utm_source=medium&amp;utm_medium=referral">Creative Christians</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What’s in this post?</h3><p>In this article, I’ll guide you on how to build a dynamic Modal component from scratch which can be a general component in your project and receive a different body every single time you use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28CVwEMWuOWNPLIQh7CUZg.png" /><figcaption>Expected result — dynamic content modal component</figcaption></figure><h3>Prerequisites:</h3><ol><li>Basic JavaScript knowledge.</li><li>Basic ReactJS knowledge.</li><li>Basic CSS knowledge.</li></ol><h3>Create a project</h3><p>Alright, so first of all, we will need a project so we can implement our new Modal component, if you already have one then feel free to pass this step and continue to the next one.</p><p>In case you don’t have a project ready for that, let&#39;s create a new project using the following command:</p><pre>npx create-react-app modal_tutorial</pre><p>This command will generate a new ReactJS application named modal_tutorial.</p><h3>Creating the Modal component</h3><p>Next, organize your newly created React application and add a new folder under the <strong>src </strong>directory called <strong>components</strong>, and inside of it create another project and name it <strong>Modal</strong> with 2 files into it: <strong>index.js &amp; index.css</strong>.</p><p>Past the following code in your <strong>index.js</strong> file:</p><pre>import React, {useEffect, useRef} from &#39;react&#39;;</pre><pre>import &#39;./index.css&#39;;</pre><pre>const Modal = ({isOpen, toggleModal, closeOnOutsideClick, children}) =&gt; {<br>    const modalRef = useRef(null);<br>    <br>    useEffect(() =&gt; {<br>       const handleClickOutside = (event) =&gt; {<br>            if (closeOnOutsideClick &amp;&amp; modalRef.current &amp;&amp; !modalRef.current.contains(event.target)) {<br>              toggleModal();<br>            }<br>       }</pre><pre>       // Bind the event listener<br>       document.addEventListener(&#39;mousedown&#39;, handleClickOutside);<br>       return() =&gt; {<br>             // Unbind the event listener<br>             document.removeEventListener(&#39;mousedown&#39;, handleClickOutside);<br>       };</pre><pre>}, [modalRef, closeOnOutsideClick, toggleModal];</pre><pre>return (<br>    &lt;div className=&quot;modal&quot; style={isOpen ? {display: &#39;none&#39;} : null}&gt;<br>       &lt;div className=&quot;modal__wrapper&quot; ref={modalRef}&gt;<br>           {children}<br>       &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>export default Modal;</pre><p>Let me explain to you what you just copied:</p><ol><li>First, we’re going to request the parent component to provide us 4 different props:</li></ol><ul><li>isOpen — Boolean, and should describe if the modal should be open right now or not.</li><li>toggleModal — Function, which should change the value of isOpen.</li><li>closeOnOutsideClick — Boolean, and should describe if we want to close the modal when we click outside of it or not.</li><li>children — HTML element (such as div) which will be the body of our modal.</li></ul><p>2. Defined a reference that will be used on the modal’s wrapper and will know its current state.</p><p>3. useEffect function, which will handle closing the modal in case we passed the closeOnOutsideClick as a truthy param.</p><p>4. The return HTML elements, that will be the wrapper of the modal and based on isOpen prop, we toggle the display of modal__wrapper div from <strong>none</strong> to <strong>flex</strong> (flex is in the CSS section below).</p><p>5. Exported the component so we can import it from other files in our project.</p><h3>Add some style:</h3><p>Let’s start by copying the following code to your <strong>index.css </strong>file:</p><pre>.modal {<br>   position: fixed;<br>   display: flex;<br>   justify-content: center;<br>   align-items: center;   z-index: 1000;<br>   left: 0;<br>   top: 0;<br>   width: 100%;<br>   height: 100%;<br>   background-color: rgba<em>(</em>0, 0, 0, 0.4<em>)</em>;<br>}</pre><pre>.modal__wrapper {<br>   position: absolute;<br>   top: 50%;<br>   width: 30%;<br>   background: #fff;<br>   text-align: center;<br>   transform: translateY<em>(</em>-50%<em>)</em>;<br>   padding: 2rem;<br>   border-radius: 18px;<br>   box-shadow: 0 0 1rem 0 #ccc;<br>   min-height: 200px;<br>   display: flex;<br>   justify-content: center;<br>   align-items: center;<br>}</pre><p>Let me explain to you what you just copied:</p><ol><li>We’ve styled the modal main div detecting it by its class name <strong>.modal</strong>, and we gave it a position fixed property together with height and width of 100%, and top and left properties at 0, so it will always fit the whole screen, next we gave it a background-color so the user will see the difference between the original screen and the opened modal.<br>We’ve also set the entire div displayed as flex and centered the whole modal so it will be displayed in the center of the screen.</li><li>Next, we’ve styled the modal’s wrapper div using its class name <strong>.modal__wrapper</strong> and we chose a position absolute and used the top property set to 50%, and transform: translateY(-50%) so it will center the modal’s wrapper to the middle of the screen even in cases that there’s a scrollbar needed.<br>After that, we gave it 30% width of the screen, aligned the text to the center of the div, and gave it some more properties of styling like padding, and box-shadow, and displayed the content of the wrapper in the center using display flex property.</li></ol><h3>Use the Modal component</h3><p>Get into your src/App.js file and inside of it, import our newly created component using the following line on the top of the file:</p><pre>import Modal from &#39;./components/Modal&#39;;</pre><p>To use the Modal, you’ll have to define a few things:</p><ol><li>Define a new state using the useState hook which will be used to toggle the modal and describe its open status, and create a new function called toggleModal which will handle the change of the state:</li></ol><pre>import React, {useState} from &#39;react&#39;;<br>import Modal from &#39;./components/Modal&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre>const App = () =&gt; {<br>   const [isModalOpen, setIsModalOpen] = useState(false);<br>   <br>   const toggleModal = () =&gt; {<br>         setIsModalOpen(!isModalOpen);<br>   }</pre><pre>return (<br>         &lt;div className=&quot;App&quot;&gt;<br>              &lt;Modal isOpen={isModalOpen} toggleModal={toggleModal} closeOnOutsideClick={true}&gt;<br>                &lt;div className=&quot;content&quot;&gt;<br>                   Your content here...<br>                &lt;/div&gt;<br>              &lt;/Modal&gt;<br>              &lt;button onClick={toggleModal}&gt;Open Modal&lt;/button&gt;<br>         &lt;/div&gt;<br>    );<br>}</pre><pre>export default App;</pre><p>Explanation:</p><ol><li>First, we’ve imported React and the useState hook so we can create a state using this hook, and we created the isModalOpen state, and initialized it to false, so the modal won’t be opened by default.</li><li>Second, we defined a new method called toggleModal which is changing the isModalOpen state to the opposite of the current state, by this way, we’ll be able to toggle it from false to true and true to false.</li><li>Next, we returned a modal with all the properties we defined in the modal component and passed isModalOpen to isOpen prop, toggleModal to the toggleModal prop, and true to closeOnOutsideClick so clicking outside of the modal will close it.</li><li>We’ve added a button to the page which will handle the modal toggle so we will be able to toggle it and we passed toggleModal to the onClick prop of it.</li></ol><h3>The Result</h3><p>Congratulations! You’ve made a dynamic modal component!</p><p>The modal should look something like that:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstreamable.com%2Fo%2Fdhgsgs&amp;display_name=Streamable&amp;url=https%3A%2F%2Fstreamable.com%2Fdhgsgs&amp;image=https%3A%2F%2Fcdn-cf-east.streamable.com%2Fimage%2Fdhgsgs.jpg%3FExpires%3D1636799580%26Signature%3DdROey7UrdZzjQBj1LkEJP6Fy6mvBtoSGjKSO5IVpZ1q7AvwbrqPku9SkkUdgTLIlyUMxVno%7EKDOa7h2oN-08B59EJe0PP25o1UO2t4HlvDaAvpH%7EjCcjnNZF6fMGxBX5p62CJxbzCc92hcrG604%7E3r1Fuote3r5yJ3--3sGlmqSOWHoubFAdK1xDBuXjvotkQBuwpGu-FLoBW6c9NVYd5m6ISejB3FsgbkvrU5T9f1VdEuBk6NozGZ1xDV2DKvCcXKmb0a4gLXs8l532X1TJD0mHLIm-ESsl86EQsSjckUWRut0T3ZrLkaWGLDIugvw9tLQ7UOcEW5zFtNCoCeA-IA__%26Key-Pair-Id%3DAPKAIEYUVEN4EVB2OKEQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=streamable" width="1182" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30cdcad676b811d90c8f6b023084b3e/href">https://medium.com/media/e30cdcad676b811d90c8f6b023084b3e/href</a></iframe><p>GitHub repository: <a href="https://github.com/RLeDEV/dynamic_modal">https://github.com/RLeDEV/dynamic_modal</a></p><p>If you want to learn more, lookup for my previous articles:</p><ul><li><a href="https://aws.plainenglish.io/white-listing-ips-to-your-website-environments-using-aws-waf-551230cbb07c">How to White-list IPs to Website Environments Using AWS Web Application Firewall</a></li><li><a href="https://aws.plainenglish.io/deploy-react-app-to-aws-s3-static-website-host-8f5cf688f3ad">How to Deploy React App to AWS S3 Static Website Host</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef32bdf6604" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>