DEV Community: Ishan SharmaThe latest articles on DEV Community by Ishan Sharma (@ishandeveloper).
https://dev.to/ishandeveloper
https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F250594%2F00b3ffda-b6cb-4bb0-8d23-416bbb421cf9.jpgDEV Community: Ishan Sharma
https://dev.to/ishandeveloper
enUI Design for DevelopersIshan SharmaMon, 05 Dec 2022 12:29:46 +0000
https://dev.to/ishandeveloper/ui-design-for-developers-2aie
https://dev.to/ishandeveloper/ui-design-for-developers-2aie<p><em>Originally posted on, my <a href="proxy.php?url=https://blog.ishandeveloper.com/design-for-devs" rel="noopener noreferrer">personal blog</a></em></p>
<h4>
As a developer,
</h4>
<h2>
Why should you even care about design?
</h2>
<p>Design is a crucial part of any digital product. Designers are responsible for the look and feel of an application, which is what makes it stand out from other similar applications.</p>
<p>Generally, The design process can be long and complicated but I feel that <strong>as a developer it's important for us to understand the principles of design</strong> because believe it or not it can actually have a significant impact on the way you think and approach a problem.</p>
<p>Especially, if you're a front-end developer, even the most basic concepts used in design tools such as layering, skew, scale and methodologies such as atomic design methodology, user journey maps etc. can help you to come up with creative solutions to your day-to-day challenges and these design patterns can help shape your code.</p>
<h4>
Hmm, okay. It's might be helpful. But,
</h4>
<h2>
Why should I learn design?
</h2>
<p>Apart from the few which I listed above. There could be countless reasons as to why you as a developer might want to learn design such as :</p>
<ol>
<li>It could help you to work more effectively with designers and may significantly reduce the back-and-forth.</li>
<li>Some small teams might not have a designer and sometimes you may want to craft your personal projects, but not necessarily have the resources & time to hire a designer.</li>
<li>It can help you to become more detail-oriented.</li>
<li>and the list can go on and on...</li>
</ol>
<p>However, <strong>I'd like to share my own journey on how & why I started with design.</strong> For this, we have to do some time travel and take a trip down the memory lane.</p>
<h4>
It was February, 2015
</h4>
<p>After getting frustrated over subscription paywalls of <a href="proxy.php?url=https://connectify.me/hotspot/" rel="noopener noreferrer">Connectify Hotspot</a> that filled up my monitor, I decided to build something of my own, which could help me in creating wifi hotspots from my desktop computer.</p>
<p>Few weeks later, I built a relatively simple desktop app for my own use case and decided to upload it on the internet for free. It crossed 25k+ downloads in less than 2 days ofc, which was the cool part β¨ xD</p>
<p>However, the sad part was that this is how it looked ππ»</p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkldgg1l32wzdj2rylvc7.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkldgg1l32wzdj2rylvc7.png" alt="Wifi Hotspot Creator | UI Design for developers | @ishandeveloper" width="629" height="622"></a></p>
<p>Yep. I still can't that this was something that I 'designed' back then. Notice those gigantic buttons with <code>10px border blue</code>. <strong>What's a color palette?</strong> I didn't even look up any hex codes! I just wrote <strong>'blue', 'red'</strong> and that's it.</p>
<h3>
However, If you think that that was bad..
</h3>
<p>Look at this one, which I had initially built (but thank god, I never published it).</p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftqg08meqel0fp3vuc4fg.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftqg08meqel0fp3vuc4fg.png" alt="Wifi Hotspot Creator | UI Design for developers | @ishandeveloper" width="635" height="647"></a></p>
<h3>
But, what's wrong with this design?
</h3>
<h4>
I mean, it does what it's supposed to, right?
</h4>
<p>That's exactly what I thought back then π .</p>
<p>Well, first and foremost apart from the fact that it straightaway <strong>looks ugly</strong>, There are three main issues, which might've crossed your mind.</p>
<ol>
<li>For starters, <strong>THE FONT</strong>. Instead of using 'Comic Sans MS', I should've gone for a more readable, accessible sans-serif font.</li>
<li>
<strong>THE COLOR SCHEME</strong>. There's no defined color palette or anything of that sort in the product. There are so many bold colors used throughout the app. Especially in the primary buttons, apart from the text, there's no real distinction between the two.</li>
<li>
<strong>CONTRAST</strong>: You may notice that in some of the parts (for example: the buttons), it's very difficult to read the text on a dark background i.e. it lacks contrast.</li>
</ol>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkvlwh5392h588sx2i3f1.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkvlwh5392h588sx2i3f1.png" alt="Start or stop hotspot | Design for developers | @ishandeveloper" width="800" height="304"></a></p>
<p>However, while learning how to design most of us tend to focus too much on just the aesthetics of designs, how they look. <strong>However, If it's not usable, even the most aesthetically pleasing design is useless.</strong></p>
<p>This is another key aspect to consider, design is not just about how a product looks, but how intuitive and easy it is to use. Designs should be predictable enough that users are able to intuitively understand how to use them.</p>
<p>For example, If you pay close attention to the <strong>Password Input Field</strong> in the design above, Once a user has typed a password, there's no way for him or her to go ahead and retrieve the password.</p>
<p>I encountered this particular thing a lot in my day-to-day use and I always had to go ahead and entirely reset my hotspot password and then update it on all of my other devices. Which was not a <em>functional issue of course, but for a user, it was just, frustrating.</em></p>
<h3>
Fast forward to today,
</h3>
<h4>
It has been 7 years since I made those mistakes..
</h4>
<p>I eventually learnt all of these things and developed a sense of design, not by reading books/articles or any theoretical concepts. But, it was just an intution that got developed over the years, after visiting thousands of websites.</p>
<p>Every single interaction on any new webpage that I visited helped me to re-iterate on my understanding of user interfaces & user experience. Similarly, every single time when an interaction within an app felt unnatural or whenever I felt annoyed while using any particular app, I always questioned that <strong>why was that the case?</strong></p>
<p>Later on, when I actually read some theory and concepts like Visual Hierarchy, Contrast Ratios, <a href="proxy.php?url=https://www.smashingmagazine.com/2016/09/the-thumb-zone-designing-for-mobile-users/" rel="noopener noreferrer">Thumb Zone Rule</a>, Consistency, White spacing etc., all of those things that I had observed and the intution that I had developed over the years all started making sense to me and helped me answer why some things were done in the way there were.</p>
<p>All of this helped me to not only improve my applications and products ofc, but they helped me in ways I didn't imagine at first. Some of them being:</p>
<h4>
1. Unicorn Developer π¦
</h4>
<p>I first heard this term in one of <a href="proxy.php?url=https://www.youtube.com/watch?v=MIepaf7ks40" rel="noopener noreferrer">Filip Hracek's talks</a>. It's commonly used to refer to people who can do both design & development. <strong>It sounds cool, no?</strong> Unicorns have always been portrayed as these magical creatures, be it cartoon shows or Harry Potter films. It certainly feel cool to be called one :)</p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3nhsznsp65mdnqcmc7on.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3nhsznsp65mdnqcmc7on.png" alt="Unicorn developer | Design for developers | @ishandeveloper" width="800" height="482"></a></p>
<h4>
2. Boosts Creativity
</h4>
<p>The reason I started with HTML & CSS was because it gave me this huge empty canvas which I could use to create and share my art with anyone in the world. Learning how to design, helps you unlock a super power that helps you to not just create but actually invision those art concepts.</p>
<p>And as I mentioned before, it can have a significant impact on the way you think and approach a problem even in code as well.</p>
<h4>
3. Effective Communcation
</h4>
<p>Once you develop a basic understanding of design, it actually helps you to respect and sometimes even question the principles behind why designers make the decisions they do, and this same thing will help you in replicating those designs with pixel-perfection. Nothing can be more frustrating for a designer than to hand over a design for a product feature, only to find that their design was changed significantly by the developer coding it.</p>
<h4>
4. Understand User Persona
</h4>
<p>The cool part about design is that instead of just making you focus on what are you building, it forces you to think about <strong>why are you building it?</strong> This ideology helps you to deeply understand the user behaviour and what they want. Apart from giving you that motivation, that you're making a change in someone's life.</p>
<p>In some cases, it could help you to handle all those edge cases in your code which might've gotten overlooked and hence helping you in squashing those bugs before they even get to see the light of day.</p>
<h4>
5. Enjoy your work more
</h4>
<p>Learning how to design helps in building products that have a perfect balance between the creative and logical aspects and one thing that I've noticed is that now I enjoy my work even more! It also gives you the ability to engage in productive conversations with designers, product managers and other stakeholders by speaking their language.</p>
<p>And when you find out that maybe a particular error state was missing in a particular design, you don't have to annoy others. You can just go ahead and solve it immediately without relying on someone else to spoon-fed you and finish your work without any delays.</p>
<p><code>If all of the things listed above, weren't cool enough. Then think about this,</code></p>
<p>Once you gain the ability to do both design & development, It gives you this awesome <strong>superpower to build whatever you can dream!</strong> It's kind of like being a one-man army. </p>
<p>You can single-handedly, think, design, develop and publish any app/service out there which you want. Isn't that incredible?</p>
<h3>
Okayyy Ishan,
</h3>
<h4>
I am convinced. But how do I get started with all this?
</h4>
<p>Wohoo, So, you've finally decided to take this up. Yay, congrats! π <em>(virtual pat on the back)</em></p>
<p>There are tons and tons of resources out there. One of my personal favourites is Gary Simon's youtube channel, <a href="proxy.php?url=https://www.youtube.com/c/designcourse" rel="noopener noreferrer">DesignCourse</a>. He has a bunch of tutorials on how to use tools like figma, creative challenges, design concepts and how to actually implement them in web.</p>
<p>One advice that I'd give is to learn the basic terminology and initial design concepts first, and then work your way up from there. You can start reading books on design theories, however at the same time, don't get bogged down by theory only. </p>
<p>Once you feel that you're comfortable enough to evaluate a design decision on the basis of specific principles, you can move on. For example, just by looking at a navbar, if you're able to say things like, "The items are too close in size, the logo seems misaligned", you're ready to put these skills in practice:)</p>
<p>I've compiled down a list of some fundamentals which would help you to get started.</p>
<h3>
Few Fundamentals
</h3>
<h4>
which may come in handy..
</h4>
<h5>
Design Tools
</h5>
<p>The first design tool that I ever used was not really a design tool at all. It was just my <strong>chrome browser</strong> :)</p>
<p>At that point, since I was most comfortable with writing <strong>HTML and CSS code</strong>. I used to just straight away open my text editor and code it away, then I'd often play around with different layouts, color palettes etc.</p>
<p>This worked surprisingly well for a while! <strong>However, As you can imagine that it quite often this process involved a lot of extra efforts</strong> since I had to write code in order to actually visualize what I was thinking and then had to completely get rid of it and start from scratch if I wanted to pivot to something else.</p>
<p>That's when I decided to explore tools like <a href="proxy.php?url=https://www.adobe.com/in/products/xd.html" rel="noopener noreferrer">Adobe XD</a> and <a href="proxy.php?url=https://figma.com" rel="noopener noreferrer">Figma</a>. These are dedicated design tools with easy to use drag & drop things and have lots of other handy things such as layers, design systems etc. which helps designers to craft these designs easily. </p>
<p>Most importantly, these tools allow you to actually build prototypes as well which you can use to pitch a concept or visualize and entire end-to-end user flow.</p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs3bnrb6yupc6ldlpyrof.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs3bnrb6yupc6ldlpyrof.png" alt="Github Wrapped 2021 | Figma | ishandeveloper" width="800" height="435"></a></p>
<h5>
Typography
</h5>
<p>Remember the odd looking 'Comic Sans MS' font that we saw earlier in my app? Yep, that was bad and things like those could've been avoided only if I had better understanding of typography back then.</p>
<p>Firstly, different fonts and typefaces have their own features and can make or break the experience. Hence, you should always choose one that better suits your design theme and style. For example, if you're looking for a font for a cartoon/illustrated website then perhaps a bold, fat and rounded font might better suit your needs.</p>
<p>In order to further enhance the user's experince, this typography can be combined with two other key fundamentals of design:</p>
<ul>
<li><strong>Visual Hierarchy</strong></li>
</ul>
<p>The relationship between different type elements in a design is vital to making that design more usable. A website with a great visual hierarchy will also help users find their information fast.</p>
<p>You can play manipulate different properties of fonts, their weights, size, style (italic or underlined) to create a better visual hierarchy. Headings, sub-headings, titles etc. are some of the examples.</p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqhvwzxl2pm2lv0b76qzr.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqhvwzxl2pm2lv0b76qzr.png" alt="Visual Hierarchy | Design for developers | @ishandeveloper" width="800" height="482"></a></p>
<ul>
<li><strong>White Space</strong></li>
</ul>
<p>The next principle you can follow is to balance the amount of space and element on the webpage. </p>
<p>Again, adding too much white space may make the UI look boring for users to use and navigate around. On the other hand, not having enough white space is actually worse, since it creates a cluttered and crowded interface, making it hard for users to find the information they need.</p>
<p>Hence, <strong>maintaining a balance</strong> between these two states is very important. </p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdp3uwgjj318imkcru6zc.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdp3uwgjj318imkcru6zc.png" alt="Whitespace | Design for developers | @ishandeveloper" width="800" height="443"></a></p>
<h5>
Colors
</h5>
<p>Colors play a significant role in any product's design. Different colors can be used to induce different emotions in a user's mind, even slight changes in shades can completely shift the visual impact.</p>
<p>One of the design fundamentals is Color Theory, which is a very vast topic and deserves an entire blog of it's own. However, we'll discuss a few basic things to know about colors.</p>
<p>The below image represents what we call, a <strong>Color Wheel</strong>. </p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnzlzxab6y6ldjsvst8gb.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnzlzxab6y6ldjsvst8gb.png" alt="Color wheel | Design for developers | @ishandeveloper" width="800" height="600"></a></p>
<p>On the basis of this, colors can be classified into various groups with regards to their tones.</p>
<ul>
<li><strong>Analogous Colors</strong></li>
</ul>
<p>Analogous means similar and is the name for a group of colours that lie immediately adjacent to each other on the colour wheel. Each of the three colours has one colour in common.</p>
<p>For example: In the above wheel, red-orange, orange-yellow and yellow-green are analogous colors.</p>
<ul>
<li><strong>Warm Colors</strong></li>
</ul>
<p>Warm colours are mostly made of Red, Orange and Yellow. They are called warm because they remind us of warm things like the sun or fire. </p>
<p>These colors tend to depict emotions of warmth, security(orange), joyful (yellow), however at the same time danger(red). It should be used carefully. Remember the two giant red buttons in my app, that we saw earlier?</p>
<ul>
<li><strong>Cool Colors</strong></li>
</ul>
<p>Cool colours are made mostly of Green, Blue and Violet. They are called cool because they remind us of cool things like a cool forest, a cold lake, sky, air or ice.</p>
<p>Cool colours tend to be psychologically soothing and can actually make people feel cooler because they can slightly lower the blood circulation and thereby decrease body temperature.</p>
<ul>
<li><strong>Neutral Colors</strong></li>
</ul>
<p>Neutral Colours are colours that are neither warm nor cool. They are the result of mixing two complementary colours (e.g Red and Green). These are all types of Brown. Black, White and Grey are are also neutral colours.</p>
<p>With enough consideration and thoughtfulness, <strong>Combinations of these colors, can be put throughout the product to induce different emotions in a user.</strong> </p>
<p>For example: Signing up for an app is a positive action hence cool colors such as <strong>blue, green</strong> can be used. Whereas, deleting an existing account is a destructive action, hence warmer colors such as <strong>red</strong> is used to depict 'danger'.</p>
<h4>
Contrast ratios
</h4>
<p>Perhaps the most important thing to consider while using any combinations of these colors to be vary of contrast, or perceived βluminanceβ. It is the difference in brightness between two colors.</p>
<p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fco941rarjfeggw3dcnag.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fco941rarjfeggw3dcnag.png" alt="Contrast ratios | Design for developers | @ishandeveloper" width="800" height="482"></a></p>
<p>There are plugins in tools such as <a href="proxy.php?url=https://www.figma.com/community/plugin/748533339900865323" rel="noopener noreferrer">Figma</a> which can help in determining the contrast ratio i.e. a ratio of the luminance of two colors.</p>
<p>When working on the web, we must always hit at least <a href="proxy.php?url=https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum.html" rel="noopener noreferrer">WCAG</a> (i.e. Web Content Accessibility Guidelines) AA color contrast guidelines, which states that we should maintain</p>
<ul>
<li>A contrast ratio of at least 4.5:1 for regular text elements</li>
<li>A contrast ratio of at least 3:1 for large text elements </li>
<li>A contrast ratio of at least 3:1 for graphical objects and UI components </li>
</ul>
<h3>
Conclusion
</h3>
<p>If you're a developer who's interested in learning more about design, or someone who had no clue about design up until this point. I hope that this was helpful to you in one way or the other or at least motivated you to explore more about design :) </p>
<p>At the end, what matters the most is that you should enjoy what you do :) Get out there and be a unicorn! π¦</p>
<p>Oh btw, If you are already a unicorn developer or you're on your journey to become one, do share your codepen / dribbble shots for sure. Here's <a href="proxy.php?url=https://dribbble.com/ishandeveloper" rel="noopener noreferrer">mine</a>!</p>
aillmvectordatabase#GithubWrapped - DO SubmissionIshan SharmaSun, 10 Jan 2021 18:44:39 +0000
https://dev.to/ishandeveloper/githubwrapped-do-submission-2fh8
https://dev.to/ishandeveloper/githubwrapped-do-submission-2fh8<h3>
Background
</h3>
<h4>
2020 has been a challenging year for all of us.
</h4>
<p>As the year is ending, I thought to take a look back at all the contributions you as an individual made to the open-source community, during these unprecedented times.</p>
<p><strong>Also since,</strong> Spotify has <strong>#SpotifyWrapped</strong>, Snapchat has <strong>#lookback</strong>, </p>
<h4>
Why not something for us, devs!?
</h4>
<p>That's exactly what motivated me to create this.</p>
<h3>
What I built
</h3>
<h4>
Presenting <strong>#GitHubWrapped</strong> !
</h4>
<p>To take a look back at all the contributions you as an individual<br>
made to the open-source community, during these unprecedented times.</p>
<h4>
How does it work?
</h4>
<p>Once you navigate to <a href="proxy.php?url=https://githubwrapped.tech">githubwrapped.tech</a>, you'll be prompted to enter your github username after which you can get your own personalized report.</p>
<h3>
UPDATE !
</h3>
<p><em>Over the last few weeks, we've <strong>crossed over 2,200 Tweets</strong> with the #GitHubWrapped hashtag and over <strong>half a million site visits</strong> in less than 6 days from the launch.</em></p>
<h3>
Category Submission:
</h3>
<p>Program for the People</p>
<h3>
App Link
</h3>
<h4>
<a href="proxy.php?url=https://githubwrapped.tech">githubwrapped.tech</a>
</h4>
<h3>
Screenshots
</h3>
<p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--CGM6x6qz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/4xey10rhc14cgf20j3ai.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--CGM6x6qz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/4xey10rhc14cgf20j3ai.png" alt="jiczm42c1f3hw2s4zfyn" width="880" height="548"></a></p>
<h4>
Reports
</h4>
<p>Each github user can generate a year in review report similar to this.</p>
<p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--sjwgKnKg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uaohywf7d1bgs8g9nqc2.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--sjwgKnKg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uaohywf7d1bgs8g9nqc2.png" alt="ishandeveloper's-report" width="880" height="1027"></a></p>
<p>Yearly reports contains your stats from the beginning of this year including number of commits, stars etc.</p>
<p>You can also save your report as an image using the 'Save Report' button and share it with the community or keep it as a memorandum :)</p>
<h4>
Tweet Bot
</h4>
<p>The celebrations don't end here! We also made our own cute octo-bot on twitter <a href="proxy.php?url=https://twitter.com/GithubWrapped">@GitHubWrapped</a>.</p>
<blockquote class="ltag__twitter-tweet">
<div class="ltag__twitter-tweet__main">
<div class="ltag__twitter-tweet__header">
<img class="ltag__twitter-tweet__profile-image" src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--3K2oc6kd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://pbs.twimg.com/profile_images/1342534659599568896/evdyZvgf_normal.jpg" alt="#GitHubWrapped profile image">
<div class="ltag__twitter-tweet__full-name">
#GitHubWrapped
</div>
<div class="ltag__twitter-tweet__username">
@githubwrapped
</div>
<div class="ltag__twitter-tweet__twitter-logo">
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--ir1kO05j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-f95605061196010f91e64806688390eb1a4dbc9e913682e043eb8b1e06ca484f.svg" alt="twitter logo">
</div>
</div>
<div class="ltag__twitter-tweet__body">
Heya, <a href="proxy.php?url=https://twitter.com/hashtag/techtwitter">#techtwitter</a> and <a href="proxy.php?url=https://twitter.com/hashtag/coders">#coders</a> !<br><br>Ever wondered why <a href="proxy.php?url=https://twitter.com/Spotify">@Spotify</a> has <a href="proxy.php?url=https://twitter.com/hashtag/SpotifyWrapped">#SpotifyWrapped</a>, while <a href="proxy.php?url=https://twitter.com/Snapchat">@Snapchat</a> has <a href="proxy.php?url=https://twitter.com/hashtag/lookback">#lookback</a>. Why not <a href="proxy.php?url=https://twitter.com/github">@github</a> ?<br><br>Presenting, <a href="proxy.php?url=https://twitter.com/hashtag/GithubWrapped">#GithubWrapped</a> π Take a look at all the contributions you made in 2020!<br><br><a href="proxy.php?url=https://t.co/cYTZX9Q2bE">githubwrapped.tech</a><br><br><a href="proxy.php?url=https://twitter.com/hashtag/100DaysOfCode">#100DaysOfCode</a> <a href="proxy.php?url=https://twitter.com/hashtag/Code">#Code</a> <a href="proxy.php?url=https://twitter.com/hashtag/YearInReview">#YearInReview</a>
</div>
<div class="ltag__twitter-tweet__date">
07:56 AM - 26 Dec 2020
</div>
<div class="ltag__twitter-tweet__actions">
<a href="proxy.php?url=https://twitter.com/intent/tweet?in_reply_to=1342740993880125441" class="ltag__twitter-tweet__actions__button">
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--fFnoeFxk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-reply-action-238fe0a37991706a6880ed13941c3efd6b371e4aefe288fe8e0db85250708bc4.svg" alt="Twitter reply action">
</a>
<a href="proxy.php?url=https://twitter.com/intent/retweet?tweet_id=1342740993880125441" class="ltag__twitter-tweet__actions__button">
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--k6dcrOn8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-retweet-action-632c83532a4e7de573c5c08dbb090ee18b348b13e2793175fea914827bc42046.svg" alt="Twitter retweet action">
</a>
<a href="proxy.php?url=https://twitter.com/intent/like?tweet_id=1342740993880125441" class="ltag__twitter-tweet__actions__button">
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--SRQc9lOp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-like-action-1ea89f4b87c7d37465b0eb78d51fcb7fe6c03a089805d7ea014ba71365be5171.svg" alt="Twitter like action">
</a>
</div>
</div>
</blockquote>
<p>Octobot stays awake all day/night to like & retweet all your tweets that use the hashtag #GitHubWrapped.</p>
<p>You can use the <strong>'Share on Twitter'</strong> button right on the web app, to share your year in review!</p>
<h3>
Link to Source Code
</h3>
<p>In case you'd like to take a look at how I did it, here's a link to the github repository<br>
</p>
<div class="ltag-github-readme-tag">
<div class="readme-overview">
<h2>
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--566lAguM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo">
<a href="proxy.php?url=https://github.com/ishandeveloper">
ishandeveloper
</a> / <a href="proxy.php?url=https://github.com/ishandeveloper/github-wrapped">
github-wrapped
</a>
</h2>
<h3>
Take a look back at all the contributions you as an individual made to the open-source community
</h3>
</div>
<div class="ltag-github-body">
<div id="readme" class="md">
<p>
<a rel="noopener noreferrer" href="proxy.php?url=https://github.com/ishandeveloper/github-wrapped./public/assets/images/favicon.png"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--HuNuaEz7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://github.com/ishandeveloper/github-wrapped./public/assets/images/favicon.png" width="25%"></a>
<a rel="noopener noreferrer" href="proxy.php?url=https://github.com/ishandeveloper/github-wrapped./public/assets/images/readme.png"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--WqH2TZ96--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://github.com/ishandeveloper/github-wrapped./public/assets/images/readme.png" width="75%"></a><br>
<a href="proxy.php?url=https://githubwrapped.tech/" rel="nofollow">Generate your report</a>
</p>
<h4>
Why do I exist?</h4>
<h3>
2020 has been a challenging year for all of us.</h3>
<p>As the year is ending, we thought to take a look back at all the contributions <strong>you</strong> as an individual
made to the open-source community, during these unprecedented times.</p>
<p>Also, since Spotify, Snapchat and other mass platforms have their own way of year wrap up, <strong>why not us?</strong></p>
<pre><a href="proxy.php?url=https://githubwrapped.tech" rel="nofollow">githubwrapped.tech</a></pre>
<h3>
Reports</h3>
<p>This web app deployed at <a href="proxy.php?url=https://githubwrapped.tech" rel="nofollow">githubwrapped.tech</a> will help you to generate yearly reports that contains your stats from the beginning of this year.</p>
<p>Including number of commits, stars etc.</p>
<p><a rel="noopener noreferrer" href="proxy.php?url=https://github.com/ishandeveloper/github-wrapped./public/assets/images/report.png"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--dxOVAci_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://github.com/ishandeveloper/github-wrapped./public/assets/images/report.png" width="75%" alt="Sample GitHub Wrapped Report"></a></p>
<p>You can also save your report as an image using the 'Save Report' button and share it with the community or keep it as a memorandum :)</p>
<h4>
Project Structure</h4>
<p>This project uses <a href="proxy.php?url=https://reactjs.org" rel="nofollow">React.Js</a> and the contents are bundled using webpack.</p>
<p>The contents in this project follow the following structure.</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto">
<pre class="notranslate"><code>ββββapi
ββββpublic
β ββββassets
ββββsrc</code></pre>β¦</div>
</div>
</div>
<div class="gh-btn-container"><a class="gh-btn" href="proxy.php?url=https://github.com/ishandeveloper/github-wrapped">View on GitHub</a></div>
</div>
<h3>
Permissive License
</h3>
<p>MIT</p>
<h3>
How I built it
</h3>
<p>I used Digital Ocean's App Platform to </p>
<ol>
<li>Host the web app, along with the backend API</li>
<li>Host a node.js twitter bot that likes & retweets all #GithubWrapped tweets</li>
</ol>
<p>Made with π for the community :)</p>
dohackathonjavascriptyearinreviewshowdevWhat Is a Virtual Machine?Ishan SharmaTue, 06 Oct 2020 16:05:06 +0000
https://dev.to/ishandeveloper/what-is-a-virtual-machine-556c
https://dev.to/ishandeveloper/what-is-a-virtual-machine-556c<h2>
Hey, Devinas!
</h2>
<p>Actually, I'll be giving a talk soon enough to teach my peers the basics of <strong>Cloud Computing</strong>. </p>
<p>What Cloud is? What happens on the server side when you enter a URL in the address bar and hit 'enter' key? How load balancers work? Pros and Cons of cloud etc.</p>
<p>Between those topics, one that I'm planning to give a brief intro about is <strong>'What is a Virtual Machine?'</strong></p>
<p>I do know what a virtual machine is, how it just runs another instance of an OS on the same hardware, and how a hypervisor manages all the resources etc.</p>
<p>But, I'm unable to come with an easy analogy or some real-life example using which I could be able to teach them out. </p>
<h4>
<strong>Any Ideas/Suggestions ?</strong>
</h4>
<p>P.S. Also, if you'd like to join the talk and discuss a few things about cloud, feel free to registeryourself <a href="proxy.php?url=https://bit.ly/30days-kickoff">here</a>. I'd love to learn together with you :) </p>
explainlikeimfivehelpbeginnersdiscussClass Attendee ActionIshan SharmaThu, 17 Sep 2020 15:39:27 +0000
https://dev.to/ishandeveloper/class-attendee-action-2c8c
https://dev.to/ishandeveloper/class-attendee-action-2c8c<h3>
My Workflow
</h3>
<p>I have made a GitHub Action named 'Class Attendee' for helping me to get over those boring 'OOPS' classes hosted by my university on Google Meet.</p>
<p>With ease:</p>
<ul>
<li>Set a scheduled time for your classes.</li>
<li>Manage your time and learn concepts at your own pace</li>
<li>Make sure that you're never short on your college attendance.
</li>
</ul>
<p><code>P.S. OOPS or any other university course is an important part of the curriculum and you should never skip it. My only intention with this action is to be able to understand and grasp these concepts by actually implementing them on my own, a practice which I'm not able to follow while attending my University Classes.</code><br>
</p>
<h3>
Submission Category:
</h3>
<p><strong>Wacky Wildcards</strong></p>
<h3>
SECRETS
</h3>
<p>Make sure to add 3 secrets in your project, by going to </p>
<pre><b>Project Settings > Secrets > New Secret.</b></pre>
<p>The Format for these 3 secrets is as below :</p>
<ul>
<li><p><b>USER_EMAIL</b> : Contains Your Google Account Email Address</p></li>
<li><p><b>USER_PASSWORD</b> : Contains Your Google Account Password</p></li>
<li><p><b>MEET_LINK</b> : The Link for the Google Meet you'd like to join.</p></li>
</ul>
<h3>
Yaml File or Link to Code
</h3>
<p>Example Workflow file</p>
<p>An example workflow to set up your class attender action quickly.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight yaml"><code><span class="na">name</span><span class="pi">:</span> <span class="s">Class Attender</span>
<span class="na">on</span><span class="pi">:</span>
<span class="c1"># Set the time here</span>
<span class="na">schedule</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">cron</span><span class="pi">:</span> <span class="s2">"</span><span class="s">0</span><span class="nv"> </span><span class="s">11</span><span class="nv"> </span><span class="s">*</span><span class="nv"> </span><span class="s">*</span><span class="nv"> </span><span class="s">*"</span> <span class="c1"># 11 AM Every Morning</span>
<span class="na">jobs</span><span class="pi">:</span>
<span class="na">build</span><span class="pi">:</span>
<span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
<span class="na">strategy</span><span class="pi">:</span>
<span class="na">matrix</span><span class="pi">:</span>
<span class="na">python-version</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">3.7</span><span class="pi">]</span>
<span class="na">steps</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v2</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Set up Python ${{ matrix.python-version }}</span>
<span class="na">uses</span><span class="pi">:</span> <span class="s">actions/setup-python@v2</span>
<span class="na">with</span><span class="pi">:</span>
<span class="na">python-version</span><span class="pi">:</span> <span class="s">${{ matrix.python-version }}</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Setup Chromedriver</span>
<span class="na">uses</span><span class="pi">:</span> <span class="s">nanasess/setup-chromedriver@master</span>
<span class="pi">-</span> <span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
<span class="s">export DISPLAY=:99</span>
<span class="s">chromedriver --url-base=/wd/hub &</span>
<span class="s">sudo Xvfb -ac :99 -screen 0 1280x1024x24 > /dev/null 2>&1 &</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Install dependencies</span>
<span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
<span class="s">python -m pip install --upgrade pip</span>
<span class="s">pip install selenium pyvirtualdisplay pause</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">RUN</span>
<span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
<span class="s">python ./script.py ${{ secrets.USER_EMAIL }} ${{ secrets.USER_PASSWORD }} ${{ secrets.MEET_LINK }}</span>
</code></pre>
</div>
<div class="ltag-github-readme-tag">
<div class="readme-overview">
<h2>
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--566lAguM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo">
<a href="proxy.php?url=https://github.com/ishandeveloper">
ishandeveloper
</a> / <a href="proxy.php?url=https://github.com/ishandeveloper/Class-Attendee-Action">
Class-Attendee-Action
</a>
</h2>
<h3>
This repository is dedicated to a GitHub Action for running a cron job, every morning at 11 AM to attend my super boring OOPS Classes.
</h3>
</div>
<div class="ltag-github-body">
<div id="readme" class="md">
<p><a rel="noopener noreferrer" href="proxy.php?url=https://github.com/ishandeveloper/Class-Attendee-Action./Images/hero.png"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--pA-8fBJi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://github.com/ishandeveloper/Class-Attendee-Action./Images/hero.png"></a></p>
<br>
<h3>
Class Attendee Action</h3>
<p>This repository is dedicated to a GitHub Action for running a cron job, every morning at 11 AM to attend my super boring <strong>OOPS</strong> Classes.</p>
<pre>THIS REPOSITORY WAS CREATED AS A PART OF ACTIONS HACKATHON HOSTED BY DEV.TO AND GITHUB, <a href="proxy.php?url=https://dev.to/ishandeveloper/class-attendee-action-2c8c" rel="nofollow">VIEW THE SUBMISSION HERE</a>
</pre>
<h3>
SECRETS</h3>
<p>Make sure to add 3 secrets in your project, by going to</p>
<pre><b>Project Settings > Secrets > New Secret.</b></pre>
<p>The Format for these 3 secrets is as below :</p>
<pre> # Contains Your Google Account Email Address
<b>USER_EMAIL</b>
# Contains Your Google Account Password
<b>USER_PASSWORD</b>
# Add the Link for the Google Meet you'd like to join.
<b>MEET_LINK</b>
</pre>
<h3>
Usage</h3>
<p>Example Workflow file</p>
<p>An example workflow to set up your class attender action quickly.</p>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">name</span>: <span class="pl-s">Class Attender</span>
<span class="pl-ent">on</span>:
<span class="pl-c"><span class="pl-c">#</span> Set the time here</span>
<span class="pl-ent">schedule</span>:
- <span class="pl-ent">cron</span>: <span class="pl-s"><span class="pl-pds">"</span>0 11 * * *<span class="pl-pds">"</span></span> <span class="pl-c"><span class="pl-c">#</span> 11 AM Every Morning</span>
<span class="pl-ent">jobs</span>:
</pre>β¦
</div>
</div>
</div>
<div class="gh-btn-container"><a class="gh-btn" href="proxy.php?url=https://github.com/ishandeveloper/Class-Attendee-Action">View on GitHub</a></div>
</div>
<h3>
Additional Resources / Info
</h3>
<p>This action uses following open-source actions under the hood to set up things easily.</p>
<div class="ltag-github-readme-tag">
<div class="readme-overview">
<h2>
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--566lAguM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo">
<a href="proxy.php?url=https://github.com/nanasess">
nanasess
</a> / <a href="proxy.php?url=https://github.com/nanasess/setup-chromedriver">
setup-chromedriver
</a>
</h2>
<h3>
ChromeDriver for use in GitHub Actions
</h3>
</div>
<div class="ltag-github-body">
<div id="readme" class="md">
<h1>
setup-chromedriver</h1>
<p>
<a href="proxy.php?url=https://github.com/nanasess/setup-chromedriver"><img alt="GitHub Actions status" src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--2AwFFIhn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://github.com/nanasess/setup-chromedriver/workflows/Test%2520chromedriver/badge.svg"></a>
<a href="proxy.php?url=https://github.com/nanasess/setup-chromedriver/blob/master/LICENSE"><img alt="LICENSE" src="proxy.php?url=https://camo.githubusercontent.com/6b3f6147bf121162052e2c5d64a3936018c6a0da4052f0358c6b39a71ae7d873/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d3432386637652e737667"></a>
</p>
<p>This action sets up a <a href="proxy.php?url=https://chromedriver.chromium.org/" rel="nofollow">ChromeDriver</a> for use in actions</p>
<h2>
OS/Platform support</h2>
<ul>
<li>ubuntu-latest, ubuntu-20.04 or ubuntu-18.04</li>
<li>macos-latest, macos-10.15</li>
<li>windows-latest, windows-2019</li>
</ul>
<h1>
Usage</h1>
<p>See <a href="proxy.php?url=https://github.com/nanasess/setup-chromedriveraction.yml">action.yml</a></p>
<h2>
for ubuntu-latest, macos-latest</h2>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">steps</span>:
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v2</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">nanasess/setup-chromedriver@v1</span>
<span class="pl-ent">with</span>:
<span class="pl-c"><span class="pl-c">#</span> Optional: do not specify to match Chrome's version</span>
<span class="pl-ent">chromedriver-version</span>: <span class="pl-s"><span class="pl-pds">'</span>88.0.4324.96<span class="pl-pds">'</span></span>
- <span class="pl-ent">run</span>: <span class="pl-s">|</span>
<span class="pl-s"> export DISPLAY=:99</span>
<span class="pl-s"> chromedriver --url-base=/wd/hub &</span>
<span class="pl-s"> sudo Xvfb -ac :99 -screen 0 1280x1024x24 > /dev/null 2>&1 & # optional</span></pre>
</div>
<h2>
for windows-latest</h2>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">steps</span>:
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v2</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">nanasess/setup-chromedriver@v1</span>
<span class="pl-ent">with</span>:
<span class="pl-c"><span class="pl-c">#</span> Optional: do not specify to match Chrome's version</span>
<span class="pl-ent">chromedriver-version</span>: <span class="pl-s"><span class="pl-pds">'</span>88.0.4324.96<span class="pl-pds">'</span></span>
- <span class="pl-ent">run</span>: <span class="pl-s">chromedriver --url-base=/wd/hub &</span></pre>
</div>
</div>
</div>
<div class="gh-btn-container"><a class="gh-btn" href="proxy.php?url=https://github.com/nanasess/setup-chromedriver">View on GitHub</a></div>
</div>
<p>Made with β₯ by <a href="proxy.php?url=https://github.com/ishandeveloper">ishandeveloper</a></p>
actionshackathongithuntIntro To React [For Beginners]Ishan SharmaSun, 13 Sep 2020 19:59:13 +0000
https://dev.to/ishandeveloper/intro-to-react-3h3p
https://dev.to/ishandeveloper/intro-to-react-3h3p<p>Okay, so if you're somewhat a beginner in web development, you must've heard people telling you that, "You should learn react" or vue or angular, etc.</p>
<p>So, <strong>what exactly is it? Should you learn it? If yes, then How to get started?</strong> We'll be discussing answers to all these questions above.</p>
<p>NOTE : This post expects you to have some good knowledge about html, css and javascript, especially some important concepts of ES6 or further patch version.</p>
<p>If you don't feel comfortable with these currently. Then, I am of the opinion that you should first know all these, before jumping on to libraries like React. If you'd like to just quickly freshen up your minds and recall important concepts of ES6, you can read my other post.</p>
<div class="ltag__link">
<a href="proxy.php?url=/ishandeveloper" class="ltag__link__link">
<div class="ltag__link__pic">
<img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F250594%2F00b3ffda-b6cb-4bb0-8d23-416bbb421cf9.jpg" alt="ishandeveloper">
</div>
</a>
<a href="proxy.php?url=/ishandeveloper/a-quick-dive-into-es6-25b2" class="ltag__link__link">
<div class="ltag__link__content">
<h2>A Quick Dive Into ES6</h2>
<h3>Ishan Sharma γ» Jul 6 '20</h3>
<div class="ltag__link__taglist">
<span class="ltag__link__tag">#javascript</span>
<span class="ltag__link__tag">#beginners</span>
<span class="ltag__link__tag">#webdev</span>
<span class="ltag__link__tag">#discuss</span>
</div>
</div>
</a>
</div>
<h3>
What I'll be covering in this article?
</h3>
<p>Before we start, I'd like to point out that I won't be able to cover, every single thing that is out there to know about react, that's just not practically possible. I'll be covering all the basics and some important concepts that can help you to get started with react. But some of the advanced concepts such as redux etc. are beyond the scope of this article.</p>
<p>Further in this article, we'll be creating a react app, similar to this. In which we'll just pass a username into the card component, and it'll fetch the data from <a href="proxy.php?url=https://dev.to">dev.to</a> API to create a profile card.</p>
<p>P.S. In focus <a class="mentioned-user" href="proxy.php?url=https://dev.to/ben">@ben</a> <a class="mentioned-user" href="proxy.php?url=https://dev.to/graciegregory">@graciegregory</a></p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F1qoebtcrsu9ysl615mbd.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F1qoebtcrsu9ysl615mbd.png" alt="project"></a></p>
<p>Okay, with all that aside. Let's jump ahead to learn.</p>
<h3>
What is React?
</h3>
<p><strong>and why is everyone so obsessed over it?</strong></p>
<p>React is a JavaScript library built by Facebook. It is used for building front-end user interfaces. The main feature of react is that it makes your UI more modular, by enabling you to divide your interface in smaller components. This model of thinking fits user interfaces well.</p>
<p>React has literally changed the way we think about web applications and user interface development and made it possible to build and manage large-scale web applications such as Facebook, Netflix and many more in a more-efficient and modular way.</p>
<h3>
How does it work?
</h3>
<p>Instead of jumping directly, into just learning react, we should first have at least an idea about how it actually works under the hood.</p>
<p>To keep it brief and simple, In layman terms, what react does is that instead of manipulating the web browser's DOM directly, It creates this <strong>Virtual DOM</strong> in memory, where it does all these manipulations.</p>
<p>It then examines what changes have been made in the Virtual DOM and then applies those changes in the browser's DOM.</p>
<p>Let's discuss about some important concepts.</p>
<h3>
A. Components
</h3>
<p>Components are the most fundamental building blocks of a react application. In React, a single web page can be divided into small blocks that represent a different part of the screen. Consider the layout below for an example.</p>
<p>Here every colored box that you can see, represents a different component.<br>
Each individual component is independent of one another and responsible both for it's visual appearances and its interactions.</p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ffmgw7sgd5ozvk35c66om.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ffmgw7sgd5ozvk35c66om.png" alt="components"></a></p>
<p>In layman terms, a component is basically just a file that contains all the html, styling and js logic in one group.</p>
<h3>
B. JSX
</h3>
<p>Since React uses JavaScript, you might be wondering, how we'll be able to create and render elements on the screen. For creating a basic element through vanilla javascript, we usually use<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">var</span> <span class="nx">header</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nf">createElement</span><span class="p">(</span><span class="dl">"</span><span class="s2">h1</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">header</span><span class="p">.</span><span class="nx">innerHTML</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Hello World !</span><span class="dl">"</span><span class="p">;</span>
</code></pre>
</div>
<p>Although this approach is totally okay and we can still use this one in React, but you can imagine, how cluttered our code would look?</p>
<p>Just to give you can example, let's try creating an unordered list, consisting of three elements, in the casual way.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code><span class="kd">const</span> <span class="nx">List</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=></span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">alphabets</span> <span class="o">=</span> <span class="p">[</span><span class="dl">"</span><span class="s2">a</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">b</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">c</span><span class="dl">"</span><span class="p">];</span>
<span class="k">return</span> <span class="nx">React</span><span class="p">.</span><span class="nf">createElement</span><span class="p">(</span>
<span class="dl">"</span><span class="s2">div</span><span class="dl">"</span><span class="p">,</span>
<span class="kc">null</span><span class="p">,</span>
<span class="nx">React</span><span class="p">.</span><span class="nf">createElement</span><span class="p">(</span><span class="dl">"</span><span class="s2">h2</span><span class="dl">"</span><span class="p">,</span> <span class="kc">null</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Alphabets</span><span class="dl">"</span><span class="p">),</span>
<span class="nx">React</span><span class="p">.</span><span class="nf">createElement</span><span class="p">(</span>
<span class="dl">"</span><span class="s2">ul</span><span class="dl">"</span><span class="p">,</span>
<span class="kc">null</span><span class="p">,</span>
<span class="nx">alphabets</span><span class="p">.</span><span class="nf">map</span><span class="p">((</span><span class="nx">item</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">React</span><span class="p">.</span><span class="nf">createElement</span><span class="p">(</span>
<span class="dl">"</span><span class="s2">li</span><span class="dl">"</span><span class="p">,</span>
<span class="p">{</span> <span class="na">className</span><span class="p">:</span> <span class="dl">"</span><span class="s2">alphabet</span><span class="dl">"</span> <span class="p">},</span>
<span class="nx">item</span>
<span class="p">);</span>
<span class="p">})</span>
<span class="p">)</span>
<span class="p">);</span>
<span class="p">};</span>
</code></pre>
</div>
<p>Looks scary for accomplishing such a simple task, right? Now, Let's try achieving the same in the JSX way.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code><span class="kd">const</span> <span class="nx">List</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=></span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">alphabets</span> <span class="o">=</span> <span class="p">[</span><span class="dl">"</span><span class="s2">a</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">b</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">c</span><span class="dl">"</span><span class="p">];</span>
<span class="k">return</span><span class="p">(</span>
<span class="p"><</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">h2</span><span class="p">></span>Alphabets<span class="p"></</span><span class="nt">h2</span><span class="p">></span>
<span class="p"><</span><span class="nt">ul</span><span class="p">></span>
<span class="si">{</span><span class="nx">alphabets</span><span class="p">.</span><span class="nf">map</span><span class="p">(</span><span class="nx">item</span><span class="o">=></span>
<span class="p"><</span><span class="nt">li</span> <span class="na">className</span><span class="p">=</span><span class="s">"alphabet"</span><span class="p">></span>item<span class="p"></</span><span class="nt">li</span><span class="p">></span>
<span class="p">)</span><span class="si">}</span>
<span class="p"></</span><span class="nt">ul</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p">)</span>
<span class="p">}</span>
</code></pre>
</div>
<p>Noticed the difference? So much less boilerplate and somewhat more elegant code. That's <strong>JSX</strong>.</p>
<p>At first sight, you might be thinking, this looks like HTML. You are not alone, every new React developer thinks the same at first. I also thought the same.</p>
<p>But, the funny thing is, <strong>it's not HTML</strong>. It is just a syntax extension to JavaScript, or you can say some sugar syntax for defining components and their positioning inside the markup. If you'd like to learn more in depth about JSX, refer to React docs, <a href="proxy.php?url=https://reactjs.org/docs/introducing-jsx.html" rel="noopener noreferrer">here</a>.</p>
<p>I believe in learning by doing approach, that's why for the rest of this tutorial we'll be exploring react by working on a very basic react project. </p>
<h3>
C. Component State
</h3>
<p>If you try to read the react documentation to figure out what state is, it can be quite difficult to grasp at first. This is why usually many of the beginner tutorials out there, tend not to cover this concept. But in my opinion, it's not that complicated and super simple to grasp and I believe it's a very important concept to learn for everyone who's trying to learn react.</p>
<p>You can imagine state of a component as the output of that component on the basis of some particular data, or a variable let's suppose. For example, In case of an hour clock, the output of the component must change after every single hour let's say from 1 AM to 2 AM. So, the output of that clock component at 1 AM, can be referred to as a state of that component.</p>
<p>Or another example, In case someone tries to visit your website and you want to display a login page to the visitor, in case they aren't logged in and display a dashboard instead, when they are logged in. Here the boolean condition whether a user is logged in or not can be referred to as state of that component.</p>
<p><strong><em>It's important to remember that whenever the state of a component changes, the component will re-render itself.</em></strong> For example, once a user has logged in we'd want to take him to the dashboard, instead of the login page.</p>
<p>We'll be seeing this in action, while we're working on our project.</p>
<h3>
1. Setting up our react project.
</h3>
<p>For testing purposes, we can quickly get set up with React by just including three scripts in our index.html file.</p>
<h4>
a. Using Global Scripts
</h4>
<div class="highlight js-code-highlight">
<pre class="highlight html"><code><span class="nt"><script </span><span class="na">src=</span><span class="s">"https://unpkg.com/react@16/umd/react.production.min.js"</span><span class="nt">></script></span>
<span class="nt"><script </span><span class="na">src=</span><span class="s">"https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"</span><span class="nt">></script></span>
<span class="nt"><script </span><span class="na">src=</span><span class="s">"https://unpkg.com/[email protected]/babel.min.js"</span><span class="nt">></script></span>
</code></pre>
</div>
<p>If you'd like to go with that approach, you can absolutely do that and still be able to follow along in this tutorial. But, In production environments, we prefer to use a few build tools since React tends to utilize some functionalities which won't work by default in browser.</p>
<p>For this tutorial, I'll be going with the latter approach, and actually setting up a production react environment.</p>
<p>But, If you've decided to go with the previous one, just please create an <strong>'app.js'</strong> file in the same directory and make sure that your <strong>'index.html'</strong> file looks similar to this.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight html"><code><span class="cp"><!DOCTYPE html></span>
<span class="nt"><html></span>
<span class="nt"><script </span><span class="na">src=</span><span class="s">"https://unpkg.com/react@16/umd/react.production.min.js"</span><span class="nt">></script></span>
<span class="nt"><script </span><span class="na">src=</span><span class="s">"https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"</span><span class="nt">></script></span>
<span class="nt"><script </span><span class="na">src=</span><span class="s">"https://unpkg.com/[email protected]/babel.min.js"</span><span class="nt">></script></span>
<span class="nt"><body></span>
<span class="nt"><div</span> <span class="na">id=</span><span class="s">"root"</span><span class="nt">></div></span>
<span class="nt"><script </span><span class="na">type=</span><span class="s">"text/babel"</span> <span class="na">src=</span><span class="s">"./app.js"</span><span class="nt">></script></span>
<span class="nt"></body></span>
<span class="nt"></html></span>
</code></pre>
</div>
<h4>
b. Using Build Tools
</h4>
<p>For those, who're going the previous approach can skip this part but for those who'd like to set up a react environment can follow along.</p>
<ol>
<li>
<p><strong>Ensure that you've node.js installed on your system.</strong> <br>
You can check this by running <strong><code>node -v</code></strong> in your terminal. </p>
<p>If you get an output with a version number xx.xx.x . Then, you're good to go!<br><br>
But, if you get some error like command not recognized, then please download and install node.js installer package from <a href="proxy.php?url=https://nodejs.org/en/download/" rel="noopener noreferrer">here</a>.</p>
</li>
<li>
<p><strong>Create a new react project</strong><br>
Once you're set up with node. Open your terminal and <code>cd</code> into your desired directory.<br>
Now, you can run this command to install <strong>create-react-app</strong> globally on your system using npm (node package manager).<br>
</p>
<pre class="highlight plaintext"><code>npm install -g create-react-app
</code></pre>
<p>It may take a few seconds, depending upon your internet connection.</p>
<p>Now, we can finally create our react project. It's pretty simple. You can just run.<br>
</p>
<pre class="highlight plaintext"><code>npx create-react-app todo
</code></pre>
<p>This may take a while. Once that's done, you can just cd into the app folder and run the app locally using<br>
</p>
<pre class="highlight shell"><code><span class="nb">cd </span>todo
npm start
</code></pre>
<p>It'll open up a browser window, and you should be able to see something like this</p>
</li>
</ol>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fj3sypvgpj6t383mlh50c.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fj3sypvgpj6t383mlh50c.png" alt="react-hello"></a></p>
<p>Congratulations, you've just created created your first react project! π</p>
<p>We'll go through everything that's happening in the code and folder structure in just a minute, but first let's clear up some unwanted clutter.</p>
<p>To speed things up, you can <strong>download these starter files</strong> from <a href="proxy.php?url=https://github.com/ishandeveloper/Intro-To-React/blob/starter-files/starter-files.zip?raw=true" rel="noopener noreferrer">here</a> and copy replace the src folder. If you've done this, then you can just run <code>npm start</code>, skip the latter part and jump to <strong>Understanding the project structure</strong>.</p>
<h4>
If you'd still prefer to do things manually instead,
</h4>
<p>Inside the 'src' folder, you must be able to see a lot of files. Let's start by cleaning these.<br>
Let's delete the all other files in src folder, till you're left with just these 3, 'App.js', 'index.js', 'index.css'.</p>
<p>You must be getting an error in your terminal. Let's fix this.</p>
<p>Open the 'index.js' file and remove all deleted imports, and serviceworker code. Till you're left with something similar to this<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="k">import</span> <span class="nx">React</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="nx">ReactDOM</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react-dom</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="dl">"</span><span class="s2">./index.css</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="nx">App</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./App</span><span class="dl">"</span><span class="p">;</span>
<span class="nx">ReactDOM</span><span class="p">.</span><span class="nf">render</span><span class="p">(<</span><span class="nc">App</span> <span class="p">/>,</span> <span class="nb">document</span><span class="p">.</span><span class="nf">getElementById</span><span class="p">(</span><span class="dl">"</span><span class="s2">root</span><span class="dl">"</span><span class="p">));</span>
</code></pre>
</div>
<p>Still facing an error? Let's open up the 'App.js' file.</p>
<p>Remove the import logo and app.css lines and replace the return statement with a h1 header. Your 'App.js' file should look like this<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="k">import</span> <span class="nx">React</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">App</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="p"><</span><span class="nt">h1</span><span class="p">></span>Hello World<span class="p"></</span><span class="nt">h1</span><span class="p">>;</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>
</code></pre>
</div>
<p>Finally, open the index.css file, select all and delete its content.</p>
<p>Make sure that you're still running the npm start command. Now you should be able to see <strong>'Hello World'</strong> in your browser window. </p>
<h3>
2. Understanding the project structure.
</h3>
<p>Let's open up our project folder in explorer or finder and you'll notice the first thing that we have is </p>
<ol>
<li>
<strong>'node_modules'</strong>. 'node_modules' simply contain all the different packages that we've installed using npm. We don't ever touch this folder very often, and you can ignore it.
</li>
</ol>
<p>A tip to keep in mind is that, we never commit node_modules folder in version control, as they can be generated on the host machine by running <code>npm install</code>.</p>
<ol>
<li><p><strong>'public'</strong> contains our index.html file, icon and a manifest file(which you can just ignore for now).</p></li>
<li><p><strong>'package.json'</strong> This file holds some scripts and name of some packages, that basically start our react project. It's just a file created by the npm.</p></li>
<li><p><strong>'src'</strong> most of our work is going to be in this folder.</p></li>
</ol>
<p>Let's open the App.js.</p>
<p>Here in our App.js file, 'App' is a component. This particular implemenation is called functional component. We write a function exactly similar to how we define a function in vanilla javascript.<br>
</p>
<p><code>function App(){}</code><br>
</p>
<p>How it differs from vanilla javascript is that instead of returning a value, it returns a component, like<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nf">App</span><span class="p">(){</span>
<span class="k">return </span><span class="p">(</span>
<span class="o"><</span><span class="nx">h1</span><span class="o">></span><span class="nx">Hello</span> <span class="nx">World</span><span class="o"><</span><span class="sr">/h1</span><span class="err">>
</span> <span class="p">)</span>
<span class="p">}</span>
</code></pre>
</div>
<p>We can also write the same in a single line, using arrow functions.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">App</span> <span class="o">=</span> <span class="p">()</span><span class="o">=></span> <span class="o"><</span><span class="nx">h1</span><span class="o">></span><span class="nx">Hello</span> <span class="nx">World</span><span class="o"><</span><span class="sr">/h1</span><span class="err">>
</span></code></pre>
</div>
<p>Now, because we want to use this component in other pages, we need to export it by using<br>
</p>
<p><code>export default App</code><br>
</p>
<p>Let's jump back to our 'index.js' file and see how this component is being used.<br>
You can see in the index.js file, what happens is we're again importing react, along with <code>ReactDOM</code>.</p>
<p>Then, we're using a method <code>ReactDOM.render</code> method to render our 'App' Component, followed by a comma and <code>document.getElementById('root')</code>.</p>
<p>Okay, so what's happening here? What happens is, that when we use ReactDOM.render method, we ask it to render the App Component, by injecting it inside the element having an id of 'root'. What react does is it takes all our javascript code and generates the desired html from that.</p>
<p>You can verify this by opening the <code>index.html</code> file in the <code>public</code> folder. You must be able to see this<br>
<br>
<code><div id="root"></div></code><br>
<br>
in the body tag.</p>
<h3>
3. Creating Dev Cards
</h3>
<p>Let's break down our initial idea of the app, showcasing three users into components. We can easily observe that the layout of these profile cards is quite similar in all three cases, except for the data enclosed in-between.</p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fm7ajz502h5ekn172s56j.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fm7ajz502h5ekn172s56j.png" alt="card"></a></p>
<p>Let's first focus on <strong>building an html layout</strong> for this component. For the sake of simplicity, I've already included all the css required for this project in <strong>index.css</strong> in the starter files.</p>
<p>In case, you didn't download the starter files and went for the manual approach, just copy-paste the css from below into your index.css file.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight css"><code> <span class="k">@import</span> <span class="sx">url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap")</span><span class="p">;</span>
<span class="k">@import</span> <span class="sx">url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css")</span><span class="p">;</span>
<span class="o">*</span> <span class="p">{</span>
<span class="nl">box-sizing</span><span class="p">:</span> <span class="n">content-box</span><span class="p">;</span>
<span class="nl">margin</span><span class="p">:</span> <span class="m">0</span><span class="p">;</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">0</span><span class="p">;</span>
<span class="nl">font-family</span><span class="p">:</span> <span class="s1">"Poppins"</span><span class="p">,</span> <span class="nb">sans-serif</span><span class="p">;</span>
<span class="p">}</span>
<span class="nd">:root</span> <span class="p">{</span>
<span class="py">--main-color</span><span class="p">:</span> <span class="m">#eee</span><span class="p">;</span>
<span class="py">--dark-color</span><span class="p">:</span> <span class="m">#2c3e50</span><span class="p">;</span>
<span class="py">--text-color</span><span class="p">:</span> <span class="m">#7f7f7f</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.wrapper</span> <span class="p">{</span>
<span class="nl">min-height</span><span class="p">:</span> <span class="m">100vh</span><span class="p">;</span>
<span class="nl">background</span><span class="p">:</span> <span class="n">var</span><span class="p">(</span><span class="n">--main-color</span><span class="p">);</span>
<span class="nl">display</span><span class="p">:</span> <span class="n">flex</span><span class="p">;</span>
<span class="nl">justify-content</span><span class="p">:</span> <span class="nb">center</span><span class="p">;</span>
<span class="nl">align-items</span><span class="p">:</span> <span class="nb">center</span><span class="p">;</span>
<span class="nl">justify-content</span><span class="p">:</span> <span class="n">space-evenly</span><span class="p">;</span>
<span class="nl">flex-wrap</span><span class="p">:</span> <span class="n">wrap</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.card</span> <span class="p">{</span>
<span class="nl">width</span><span class="p">:</span> <span class="m">300px</span><span class="p">;</span>
<span class="nl">height</span><span class="p">:</span> <span class="m">450px</span><span class="p">;</span>
<span class="nl">background</span><span class="p">:</span> <span class="no">white</span><span class="p">;</span>
<span class="nl">margin</span><span class="p">:</span> <span class="m">1rem</span><span class="p">;</span>
<span class="nl">display</span><span class="p">:</span> <span class="n">flex</span><span class="p">;</span>
<span class="nl">flex-direction</span><span class="p">:</span> <span class="n">column</span><span class="p">;</span>
<span class="nl">justify-content</span><span class="p">:</span> <span class="n">space-between</span><span class="p">;</span>
<span class="nl">box-shadow</span><span class="p">:</span> <span class="m">0px</span> <span class="m">0px</span> <span class="m">5px</span> <span class="m">#233942</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.card</span> <span class="nt">img</span> <span class="p">{</span>
<span class="nl">background</span><span class="p">:</span> <span class="n">var</span><span class="p">(</span><span class="n">--main-color</span><span class="p">);</span>
<span class="nl">margin-top</span><span class="p">:</span> <span class="m">30px</span><span class="p">;</span>
<span class="nl">border-radius</span><span class="p">:</span> <span class="m">50%</span><span class="p">;</span>
<span class="nl">position</span><span class="p">:</span> <span class="nb">absolute</span><span class="p">;</span>
<span class="nl">width</span><span class="p">:</span> <span class="m">150px</span><span class="p">;</span>
<span class="nl">height</span><span class="p">:</span> <span class="m">150px</span><span class="p">;</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">0.15rem</span><span class="p">;</span>
<span class="nl">border</span><span class="p">:</span> <span class="m">0.2rem</span> <span class="nb">solid</span> <span class="no">black</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.user-image</span> <span class="p">{</span>
<span class="nl">position</span><span class="p">:</span> <span class="nb">relative</span><span class="p">;</span>
<span class="nl">width</span><span class="p">:</span> <span class="m">100%</span><span class="p">;</span>
<span class="nl">height</span><span class="p">:</span> <span class="m">200px</span><span class="p">;</span>
<span class="nl">display</span><span class="p">:</span> <span class="n">flex</span><span class="p">;</span>
<span class="nl">justify-content</span><span class="p">:</span> <span class="nb">center</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.user-image</span><span class="nd">:before</span> <span class="p">{</span>
<span class="nl">content</span><span class="p">:</span> <span class="s1">""</span><span class="p">;</span>
<span class="nl">height</span><span class="p">:</span> <span class="m">125px</span><span class="p">;</span>
<span class="nl">width</span><span class="p">:</span> <span class="m">100%</span><span class="p">;</span>
<span class="nl">background</span><span class="p">:</span> <span class="n">var</span><span class="p">(</span><span class="n">--dark-color</span><span class="p">);</span>
<span class="p">}</span>
<span class="nc">.user-info</span> <span class="p">{</span>
<span class="nl">display</span><span class="p">:</span> <span class="n">flex</span><span class="p">;</span>
<span class="nl">flex-direction</span><span class="p">:</span> <span class="n">column</span><span class="p">;</span>
<span class="nl">align-items</span><span class="p">:</span> <span class="nb">center</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.user-info</span> <span class="nc">.name</span> <span class="p">{</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">1.25rem</span><span class="p">;</span>
<span class="nl">text-transform</span><span class="p">:</span> <span class="nb">uppercase</span><span class="p">;</span>
<span class="nl">font-weight</span><span class="p">:</span> <span class="m">600</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.user-info</span> <span class="nc">.handle</span> <span class="p">{</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">0.9rem</span><span class="p">;</span>
<span class="nl">font-weight</span><span class="p">:</span> <span class="m">500</span><span class="p">;</span>
<span class="nl">color</span><span class="p">:</span> <span class="n">var</span><span class="p">(</span><span class="n">--text-color</span><span class="p">);</span>
<span class="p">}</span>
<span class="nc">.user-info</span> <span class="nc">.summary</span> <span class="p">{</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">0.75rem</span> <span class="m">1rem</span><span class="p">;</span>
<span class="nl">text-align</span><span class="p">:</span> <span class="nb">center</span><span class="p">;</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">0.75rem</span><span class="p">;</span>
<span class="nl">font-weight</span><span class="p">:</span> <span class="m">400</span><span class="p">;</span>
<span class="nl">color</span><span class="p">:</span> <span class="n">var</span><span class="p">(</span><span class="n">--text-color</span><span class="p">);</span>
<span class="p">}</span>
<span class="nc">.location</span> <span class="p">{</span>
<span class="nl">text-align</span><span class="p">:</span> <span class="nb">center</span><span class="p">;</span>
<span class="nl">font-weight</span><span class="p">:</span> <span class="m">400</span><span class="p">;</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">0.8rem</span><span class="p">;</span>
<span class="nl">color</span><span class="p">:</span> <span class="n">var</span><span class="p">(</span><span class="n">--text-color</span><span class="p">);</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">2.5rem</span> <span class="m">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.location</span><span class="nd">::before</span> <span class="p">{</span>
<span class="nl">font-family</span><span class="p">:</span> <span class="s1">"Font Awesome 5 Free"</span><span class="p">;</span>
<span class="nl">font-weight</span><span class="p">:</span> <span class="m">900</span><span class="p">;</span>
<span class="nl">content</span><span class="p">:</span> <span class="s1">"\f3c5"</span><span class="p">;</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">0</span> <span class="m">0.2rem</span><span class="p">;</span>
<span class="p">}</span>
</code></pre>
</div>
<p>Inside the src folder, let's create a new file <strong>card.js</strong>. Here, we'll be creating our card component.</p>
<p>Let's start by importing react and writing boilerplate function for our card.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code> <span class="k">import</span> <span class="nx">React</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">Card</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span><span class="p">(</span>
<span class="o"><</span><span class="nx">h1</span><span class="o">></span><span class="nx">This</span> <span class="nx">is</span> <span class="nx">a</span> <span class="nx">Card</span><span class="o"><</span><span class="sr">/h1</span><span class="err">>
</span> <span class="p">)</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">Card</span><span class="p">;</span>
</code></pre>
</div>
<p>Let's save the changes and open our browser to see the results. Wait, it's not showing up? That's because we haven't imported this in our <code>App</code> component.</p>
<p>To fix this, let' open our <strong>App.js</strong> file and replace the <code><h1>Hello World</h1></code> with<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code> <span class="k">import</span> <span class="nx">React</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="nx">Card</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./card</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">App</span><span class="p">(){</span>
<span class="k">return </span><span class="p">(</span>
<span class="o"><</span><span class="nx">div</span> <span class="kd">class</span><span class="o">=</span><span class="dl">"</span><span class="s2">wrapper</span><span class="dl">"</span><span class="o">></span>
<span class="o"><</span><span class="nx">Card</span> <span class="o">/></span>
<span class="o"><</span><span class="sr">/div</span><span class="err">>
</span> <span class="p">);</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>
</code></pre>
</div>
<p>Now you should be able to see, something like this in your browser</p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9a9qzb9390ucawi5h2zw.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9a9qzb9390ucawi5h2zw.png" alt="browser"></a></p>
<p>Although, this works, but if you open up your <strong>console</strong> (Ctrl/Cmd + Shift + J - Chrome, Ctrl/Cmd + Shift + K - FireFox). You must see a warning similar to this </p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fsn4a9j0ph8dlspir3a29.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fsn4a9j0ph8dlspir3a29.png" alt="warning"></a></p>
<p>** Why are we getting this warning message? **<br><br>
This is because if you look closely in the App function, the div that we're returning has a <code>class</code> of wrapper. Although, this is the exact way how we define a class in html, but remember I mentioned earlier, this is not <code>html</code> but <code>JSX</code> ?</p>
<p>Because, JavaScript already has a <code>class</code> keyword used for a constructor, that's why we can't use <code>class</code> here, to fix this React came up with <code>className</code>. We can fix this by replacing our <code>class</code> with <code>className</code> like this<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="k">import</span> <span class="nx">React</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="nx">Card</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./card</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">App</span><span class="p">(){</span>
<span class="k">return </span><span class="p">(</span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"wrapper"</span><span class="p">></span>
<span class="p"><</span><span class="nc">Card</span> <span class="p">/></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p">);</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>
</code></pre>
</div>
<p>Once you do that, any warnings in the console would get resolved.</p>
<p>With that aside, let's jump back to our <strong>card.js</strong> file and build our html layout. I've already created a layout with the same classes that were used in our css to speed things up a little bit.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="kd">function</span> <span class="nf">Card</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return </span><span class="p">(</span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"card"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-image"</span><span class="p">></span>
<span class="p"><</span><span class="nt">img</span> <span class="na">src</span><span class="p">=</span><span class="s">"user.png"</span> <span class="na">alt</span><span class="p">=</span><span class="s">"User Profile"</span><span class="p">></</span><span class="nt">img</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-info"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"name"</span><span class="p">></span>John Doe<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"handle"</span><span class="p">></span>@johndoe<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"summary"</span><span class="p">></span>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"location"</span><span class="p">></span>New York<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p">);</span>
<span class="p">}</span>
</code></pre>
</div>
<p>Once you save the changes, you should be able to see something like this in your browser. </p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fxqovmweggzwnjqat2ohq.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fxqovmweggzwnjqat2ohq.png" alt="johndoe"></a></p>
<p>Congratulations for making this far! Our app is finally taking it's shape. But this is all just static data, right? We want to showcase actual user data instead, on the basis of username. </p>
<p>For that we can use the built in Fetch API method in javascript to retrieve dev.to user's data from this endpoint : <a href="proxy.php?url=https://dev.to/api/users/by_username?url=bob">https://dev.to/api/users/by_username?url=bob</a> . Replacing <code>bob</code> with your username. This endpoint sends a json data with the below structure, that we can then parse and display in our component.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight json"><code><span class="w"> </span><span class="p">{</span><span class="w">
</span><span class="nl">"type_of"</span><span class="p">:</span><span class="w"> </span><span class="s2">"user"</span><span class="p">,</span><span class="w">
</span><span class="nl">"id"</span><span class="p">:</span><span class="w"> </span><span class="mi">1234</span><span class="p">,</span><span class="w">
</span><span class="nl">"username"</span><span class="p">:</span><span class="w"> </span><span class="s2">"bob"</span><span class="p">,</span><span class="w">
</span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"bob"</span><span class="p">,</span><span class="w">
</span><span class="nl">"summary"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Hello, world"</span><span class="p">,</span><span class="w">
</span><span class="nl">"twitter_username"</span><span class="p">:</span><span class="w"> </span><span class="s2">"bob"</span><span class="p">,</span><span class="w">
</span><span class="nl">"github_username"</span><span class="p">:</span><span class="w"> </span><span class="s2">"bob"</span><span class="p">,</span><span class="w">
</span><span class="nl">"website_url"</span><span class="p">:</span><span class="w"> </span><span class="kc">null</span><span class="p">,</span><span class="w">
</span><span class="nl">"location"</span><span class="p">:</span><span class="w"> </span><span class="s2">"New York"</span><span class="p">,</span><span class="w">
</span><span class="nl">"joined_at"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Jan 1, 2017"</span><span class="p">,</span><span class="w">
</span><span class="nl">"profile_image"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://res.cloudinary.com/...jpeg"</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre>
</div>
<p>The simplest way to use fetch API in javascript is to use it like this<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code> <span class="kd">let</span> <span class="nx">username</span><span class="o">=</span><span class="dl">"</span><span class="s2">ishandeveloper</span><span class="dl">"</span><span class="p">;</span> <span class="c1">// You can write your username here</span>
<span class="nf">fetch</span><span class="p">(</span><span class="s2">`https://dev.to/api/users/by_username?url=</span><span class="p">${</span><span class="nx">username</span><span class="p">}</span><span class="s2">`</span><span class="p">)</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nf">json</span><span class="p">())</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="nx">data</span><span class="p">);</span>
</code></pre>
</div>
<p>But, how can we use this in our react app and we want to make sure to call this fetch method, only when a component is mounted/injected in the app tree. To do this, we'll have to use something called <strong>hooks</strong>.</p>
<p>Hooks are basically just some functions, that let us to fire up a callback, in certain events of our component. You can read more on that <a href="proxy.php?url=https://reactjs.org/docs/hooks-overview.html" rel="noopener noreferrer">here</a>.</p>
<p>For our goal, we'll be using the <code>useState</code> and <code>useEffect</code> hook.</p>
<p><strong>a. useState()</strong> hook allows one to declare a state variable inside a function.</p>
<p><strong>b. useEffect()</strong> hook allows functional components to manipulate DOM elements by executing a callback before each render. </p>
<p>Before we use any of them, we should import them from the react module, by replacing the <code>import React from 'react'</code> with<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code> <span class="k">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span><span class="nx">useState</span><span class="p">,</span> <span class="nx">useEffect</span><span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">react</span><span class="dl">'</span><span class="p">;</span>
</code></pre>
</div>
<p>So, let's write our function for fetching the data from API. We'll use <code>useEffect</code> hook to call a function that fetches the data.</p>
<p>We can simply do this by writing a callback function like this, before the return statement inside the functional component.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="kd">let</span> <span class="nx">user</span><span class="o">=</span><span class="p">{};</span>
<span class="nf">useEffect</span><span class="p">(()</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">async</span> <span class="kd">function</span> <span class="nf">fetchData</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">username</span><span class="o">=</span><span class="dl">"</span><span class="s2">ishandeveloper</span><span class="dl">"</span><span class="p">;</span> <span class="c1">// You can write your username here</span>
<span class="c1">// Retrieves json data from DEV API</span>
<span class="kd">let</span> <span class="nx">dev_data</span> <span class="o">=</span> <span class="k">await</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`https://dev.to/api/users/by_username?url=</span><span class="p">${</span><span class="nx">username</span><span class="p">}</span><span class="s2">`</span><span class="p">)</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nf">json</span><span class="p">())</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="nx">data</span><span class="p">);</span>
<span class="nx">user</span><span class="o">=</span><span class="nx">dev_data</span><span class="p">;</span> <span class="c1">// Sets the user data</span>
<span class="p">}</span>
<span class="nf">fetchData</span><span class="p">();</span> <span class="c1">// Calls the above function</span>
<span class="p">},</span> <span class="p">[]</span> <span class="p">);</span>
</code></pre>
</div>
<p>In the above code, we're passing a callback function in the useEffect hook, and creating another async function <strong><em>fetchData()</em></strong> inside that callback and calling that async function. This is because, <em>using async directly in the useEffect function is not permitted</em>. </p>
<p>You may also notice that we're passing an empty array ([]) as a second parameter to the useEffect. Why is that? That is because, by default the </p>
<p><strong>useEffect callback is run every time when a component is either mounted or updated.</strong></p>
<p>So, what's the issue then? Here's the catch. Using this approach, we get stuck in kind of a nastly loop. Because we're fetching the data when the component is mounted and then updating the data, on updating the data the component again re-renders, firing the useEffect callback, and hence we're stuck in a forever loop. </p>
<p>To fix this, we pass an array as a second argument, to avoid activating it on component updates. You can read more on this in the docs, by scrolling down to the last highlighted note <a href="proxy.php?url=https://reactjs.org/docs/hooks-effect.html" rel="noopener noreferrer">here</a>.</p>
<p><strong>Although, it may seem like everything should work as expected,</strong> but the above code won't re-render the component, that is because we're not changing the state of the component. <strong><em>We need to explicitly tell react that the state of a component is changed.</em></strong> To achieve this, we we'll need to use the <code>useState</code> hook.</p>
<p>We can use it to store our user data like this<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="kd">const</span> <span class="p">[</span><span class="nx">user</span><span class="p">,</span> <span class="nx">setUser</span><span class="p">]</span> <span class="o">=</span> <span class="nf">useState</span><span class="p">({});</span>
</code></pre>
</div>
<h4>
Let's break this down
</h4>
<p>inside the <code>useState</code> method, we can add the initial value of the user variable, that we'd like to store, it can be an object, array, boolean, string, number anything. </p>
<p>The <code>useState</code> method, returns an array of two things, first is the value of the variable itself and second is a callback function that can be used to change the value of that variable.</p>
<p>So, instead of using <code>user=dev_data</code> in our above code, we'd call the <code>setUser</code> method inside the useEffect to update the user data. With these two changes, our above code would become<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="kd">const</span> <span class="p">[</span><span class="nx">user</span><span class="p">,</span> <span class="nx">setUser</span><span class="p">]</span> <span class="o">=</span> <span class="nf">useState</span><span class="p">({});</span>
<span class="nf">useEffect</span><span class="p">(()</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">async</span> <span class="kd">function</span> <span class="nf">fetchData</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">username</span><span class="o">=</span><span class="dl">"</span><span class="s2">ishandeveloper</span><span class="dl">"</span><span class="p">;</span> <span class="c1">// You can write your username here</span>
<span class="c1">// Retrieves json data from DEV API</span>
<span class="kd">let</span> <span class="nx">dev_data</span> <span class="o">=</span> <span class="k">await</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`https://dev.to/api/users/by_username?url=</span><span class="p">${</span><span class="nx">username</span><span class="p">}</span><span class="s2">`</span><span class="p">)</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nf">json</span><span class="p">())</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="nx">data</span><span class="p">);</span>
<span class="nf">setUser</span><span class="p">(</span><span class="nx">dev_data</span><span class="p">);</span> <span class="c1">// Sets the user data</span>
<span class="p">}</span>
<span class="nf">fetchData</span><span class="p">();</span> <span class="c1">// Calls the above function</span>
<span class="p">},</span> <span class="p">[]</span> <span class="p">);</span>
</code></pre>
</div>
<h4>
Perfect, we're almost done! π
</h4>
<p>Now that we have the data, let's pass it into our JSX code. In JSX, whenever we want to use JavaScript code inside the html looking tags, we enclose that javascript code with curly brackets <code>{}</code>.</p>
<p>On the basis of properties sent by the API Endpoint (mentioned above), here's how we can format that data in our jsx code.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="k">return </span><span class="p">(</span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"card"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-image"</span><span class="p">></span>
<span class="p"><</span><span class="nt">img</span> <span class="na">src</span><span class="p">=</span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">profile_image</span><span class="si">}</span> <span class="na">alt</span><span class="p">=</span><span class="s">"User Profile"</span><span class="p">></</span><span class="nt">img</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-info"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"name"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">name</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"handle"</span><span class="p">></span>@<span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">username</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"summary"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">summary</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"location"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">location</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p">);</span>
</code></pre>
</div>
<p>With this, your entire code in card.js should look like this<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code> <span class="k">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span><span class="nx">useState</span><span class="p">,</span> <span class="nx">useEffect</span><span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">react</span><span class="dl">'</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">Card</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">const</span> <span class="p">[</span><span class="nx">user</span><span class="p">,</span> <span class="nx">setUser</span><span class="p">]</span> <span class="o">=</span> <span class="nf">useState</span><span class="p">({});</span>
<span class="nf">useEffect</span><span class="p">(()</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">async</span> <span class="kd">function</span> <span class="nf">fetchData</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">username</span><span class="o">=</span><span class="dl">"</span><span class="s2">ishandeveloper</span><span class="dl">"</span><span class="p">;</span> <span class="c1">// You can write your username here</span>
<span class="kd">let</span> <span class="nx">dev_data</span> <span class="o">=</span> <span class="k">await</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`https://dev.to/api/users/by_username?url=</span><span class="p">${</span><span class="nx">username</span><span class="p">}</span><span class="s2">`</span><span class="p">)</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nf">json</span><span class="p">())</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="nx">data</span><span class="p">);</span>
<span class="nf">setUser</span><span class="p">(</span><span class="nx">dev_data</span><span class="p">);</span>
<span class="p">}</span>
<span class="nf">fetchData</span><span class="p">();</span>
<span class="p">},</span> <span class="p">[]</span> <span class="p">);</span>
<span class="k">return </span><span class="p">(</span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"card"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-image"</span><span class="p">></span>
<span class="p"><</span><span class="nt">img</span> <span class="na">src</span><span class="p">=</span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">profile_image</span><span class="si">}</span> <span class="na">alt</span><span class="p">=</span><span class="s">"User Profile"</span><span class="p">></</span><span class="nt">img</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-info"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"name"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">name</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"handle"</span><span class="p">></span>@<span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">username</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"summary"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">summary</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"location"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">location</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p">);</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">Card</span><span class="p">;</span>
</code></pre>
</div>
<p>With this done, you should be able to see something similar to this in your browser.</p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fuoieu4b55peypq1ioa3r.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fuoieu4b55peypq1ioa3r.png" alt="result-1"></a></p>
<p>Congratulations and be proud of yourself for making this far! You really deserve a pat on the back π€</p>
<h4>
But we're not done yet.
</h4>
<h3>
4. Re-Using Components
</h3>
<p>This is what I consider to be one of the best things about React. Remember? Our initial goal was to create something similar to this.</p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fej0kmh50gql7qvwvwfx7.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fej0kmh50gql7qvwvwfx7.png" alt="project"></a></p>
<p>In the above visualization, we've three cards showcasing three different profiles instead of one. So, how can we do that? It's pretty simple actually.</p>
<p>Let's open our <code>App.js</code> file. Here's how it looks like currently, right?<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="k">import</span> <span class="nx">React</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="nx">Card</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./card</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">App</span><span class="p">(){</span>
<span class="k">return </span><span class="p">(</span>
<span class="o"><</span><span class="nx">div</span> <span class="kd">class</span><span class="o">=</span><span class="dl">"</span><span class="s2">wrapper</span><span class="dl">"</span><span class="o">></span>
<span class="o"><</span><span class="nx">Card</span> <span class="o">/></span>
<span class="o"><</span><span class="sr">/div</span><span class="err">>
</span> <span class="p">);</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>
</code></pre>
</div>
<p>You can observe that we've written a <code><Card /></code> tag here to create a Card Component. We can just duplicate this, twice to get 3 instances of this card Component.</p>
<p>Additionally we can also pass custom properties in this tag markup, these are called <strong>props</strong>, let's pass the usernames of different DEV users as <code>username</code> attribute.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="k">import</span> <span class="nx">React</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">react</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="nx">Card</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./card</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">App</span><span class="p">(){</span>
<span class="k">return </span><span class="p">(</span>
<span class="o"><</span><span class="nx">div</span> <span class="kd">class</span><span class="o">=</span><span class="dl">"</span><span class="s2">wrapper</span><span class="dl">"</span><span class="o">></span>
<span class="o"><</span><span class="nx">Card</span> <span class="nx">username</span><span class="o">=</span><span class="dl">"</span><span class="s2">ben</span><span class="dl">"</span><span class="o">/></span>
<span class="o"><</span><span class="nx">Card</span> <span class="nx">username</span><span class="o">=</span><span class="dl">"</span><span class="s2">ishandeveloper</span><span class="dl">"</span><span class="o">/></span>
<span class="o"><</span><span class="nx">Card</span> <span class="nx">username</span><span class="o">=</span><span class="dl">"</span><span class="s2">graciegregory</span><span class="dl">"</span><span class="o">/></span>
<span class="o"><</span><span class="sr">/div</span><span class="err">>
</span> <span class="p">);</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>
</code></pre>
</div>
<p>Hit save, and let's see the changes in our browser.</p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgysjezgjmcndzratk1yy.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgysjezgjmcndzratk1yy.png" alt="result-2"></a></p>
<h3>
Wait, Something's weird.
</h3>
<p>Don't all of these look the same?</p>
<p>Yes, they do. Because although we've passed a username attribute in our cards, we're not using it. </p>
<p><strong>Let's fix this.</strong> Open up <code>card.js</code> file in your editor.</p>
<ul>
<li>The first thing that we'll need to do is accept those <code>username</code> props in our functional component. </li>
</ul>
<p>Let's do that by adding a <code>props</code> parameter in the function. So that our function becomes like this<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nf">Card</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
<span class="p">...........</span>
<span class="p">}</span>
</code></pre>
</div>
<p>Now we'll need to replace our hard-coded username with this username prop. It's pretty easy, just replace the <code>let username="ishandeveloper"</code> with <code>let username=props.username</code><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="nf">useEffect</span><span class="p">(()</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">async</span> <span class="kd">function</span> <span class="nf">fetchData</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">username</span><span class="o">=</span><span class="nx">props</span><span class="p">.</span><span class="nx">username</span><span class="p">;</span>
<span class="p">...........</span>
</code></pre>
</div>
<p>Hit save, and that's it. You've successfully completed the whole project! π</p>
<h3>
Here's the whole source code for card.js
</h3>
<h4>
in case you need it
</h4>
<div class="highlight js-code-highlight">
<pre class="highlight jsx"><code><span class="k">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span><span class="nx">useState</span><span class="p">,</span> <span class="nx">useEffect</span><span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">react</span><span class="dl">'</span><span class="p">;</span>
<span class="kd">function</span> <span class="nf">Card</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="p">[</span><span class="nx">user</span><span class="p">,</span> <span class="nx">setUser</span><span class="p">]</span> <span class="o">=</span> <span class="nf">useState</span><span class="p">({});</span>
<span class="nf">useEffect</span><span class="p">(()</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">async</span> <span class="kd">function</span> <span class="nf">fetchData</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">username</span><span class="o">=</span><span class="nx">props</span><span class="p">.</span><span class="nx">username</span><span class="p">;</span> <span class="c1">// You can write your username here</span>
<span class="kd">let</span> <span class="nx">dev_data</span> <span class="o">=</span> <span class="k">await</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`https://dev.to/api/users/by_username?url=</span><span class="p">${</span><span class="nx">username</span><span class="p">}</span><span class="s2">`</span><span class="p">)</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nf">json</span><span class="p">())</span>
<span class="p">.</span><span class="nf">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="nx">data</span><span class="p">);</span>
<span class="nf">setUser</span><span class="p">(</span><span class="nx">dev_data</span><span class="p">);</span>
<span class="p">}</span>
<span class="nf">fetchData</span><span class="p">();</span>
<span class="p">},</span> <span class="p">[]</span> <span class="p">);</span>
<span class="k">return </span><span class="p">(</span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"card"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-image"</span><span class="p">></span>
<span class="p"><</span><span class="nt">img</span> <span class="na">src</span><span class="p">=</span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">profile_image</span><span class="si">}</span> <span class="na">alt</span><span class="p">=</span><span class="s">"User Profile"</span><span class="p">></</span><span class="nt">img</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"user-info"</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"name"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">name</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"handle"</span><span class="p">></span>@<span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">username</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"summary"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">summary</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">className</span><span class="p">=</span><span class="s">"location"</span><span class="p">></span><span class="si">{</span><span class="nx">user</span><span class="p">.</span><span class="nx">location</span><span class="si">}</span><span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p">);</span>
<span class="p">}</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">Card</span><span class="p">;</span>
</code></pre>
</div>
<p>If you'd like to download the project files, or see a live demo of the project, you can visit this repository.</p>
<div class="ltag-github-readme-tag">
<div class="readme-overview">
<h2>
<img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo">
<a href="proxy.php?url=https://github.com/ishandeveloper" rel="noopener noreferrer">
ishandeveloper
</a> / <a href="proxy.php?url=https://github.com/ishandeveloper/Intro-To-React" rel="noopener noreferrer">
Intro-To-React
</a>
</h2>
<h3>
This repository contains the starter files and final project files for the Intro To React article published by me on Dev.to and Personal Blog.
</h3>
</div>
<div class="ltag-github-body">
<div id="readme" class="md">
<p><a rel="noopener noreferrer" href="proxy.php?url=https://github.com/ishandeveloper/Intro-To-React./hero.png"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.com%2Fishandeveloper%2FIntro-To-React.%2Fhero.png" width="100%"></a></p>
<p>This repository contains the starter files and final project files for the Intro To React article published by me on <a href="proxy.php?url=http://links.ishandeveloper.com/react" rel="nofollow noopener noreferrer">Dev.to</a> and <a href="proxy.php?url=https://blog.ishandeveloper.com/react-intro" rel="nofollow noopener noreferrer">Personal Blog</a></p>
<p>Built in <b>React.js</b> with β€οΈ</p>
<div class="markdown-heading">
<h4 class="heading-element">View Live Demo</h4>
</div>
<pre><a href="proxy.php?url=http://devcards.ishandeveloper.com/" rel="nofollow noopener noreferrer"><b>devcards.ishandeveloper.com</b></a></pre>
<div class="markdown-heading">
<h2 class="heading-element">Setup</h2>
</div>
<div class="markdown-heading">
<h5 class="heading-element">Clone the repository</h5>
</div>
<div class="highlight highlight-source-shell notranslate position-relative overflow-auto js-code-highlight">
<pre>git clone https://github.com/ishandeveloper/Intro-To-React.git</pre>
</div>
<div class="markdown-heading">
<h5 class="heading-element">Move to the desired folder</h5>
</div>
<div class="highlight highlight-source-shell notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-c1">cd</span> <span class="pl-cce">\I</span>ntro-To-React</pre>
</div>
<div class="markdown-heading">
<h5 class="heading-element">To install the dependencies, simply write</h5>
</div>
<div class="highlight highlight-source-shell notranslate position-relative overflow-auto js-code-highlight">
<pre>npm install</pre>
</div>
<div class="markdown-heading">
<h5 class="heading-element">To run the app, simply write</h5>
</div>
<div class="highlight highlight-source-shell notranslate position-relative overflow-auto js-code-highlight">
<pre>npm start</pre>
</div>
<div class="markdown-heading">
<h2 class="heading-element">Learn More</h2>
</div>
<p>You can learn more in the <a href="proxy.php?url=https://facebook.github.io/create-react-app/docs/getting-started" rel="nofollow noopener noreferrer">Create React App documentation</a>.</p>
<div class="markdown-heading">
<h5 class="heading-element">Made with β₯ by <a href="proxy.php?url=https://github.com/ishandeveloper" rel="noopener noreferrer">ishandeveloper</a>
</h5>
</div>
<p><a href="proxy.php?url=https://github.com/ishandeveloper" rel="noopener noreferrer"><img src="proxy.php?url=https://camo.githubusercontent.com/626238757866864b3d04ed0c9c43cfc9f8c5983b3c1f085362967381d24761e4/68747470733a2f2f666f7274686562616467652e636f6d2f696d616765732f6261646765732f6275696c742d776974682d6c6f76652e737667" alt="forthebadge"></a></p>
</div>
<br>
<br>
</div>
<br>
<div class="gh-btn-container"><a class="gh-btn" href="proxy.php?url=https://github.com/ishandeveloper/Intro-To-React" rel="noopener noreferrer">View on GitHub</a></div>
<br>
</div>
<br>
<p>This was all about this tutorial, I hope this helped you to grasp onto some of the basic and most important aspects of react that can help you to get started easily. </p>
<p>We can discuss more on somewhat advanced topics such as Redux, Context API etc. in futher articles. I hope you enjoyed this one and any feedback we'd be highly appreciated.</p>
<p>This post is a part of my 'Intro' series, in which I'll be giving a beginner-friendly introduction to some of the most fascinating technologies, tools and frameworks.</p>
<p>If you're interested, I'm sure, you'd love to read this one</p>
<div class="ltag__link">
<a href="proxy.php?url=/ishandeveloper" class="ltag__link__link">
<div class="ltag__link__pic">
<img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F250594%2F00b3ffda-b6cb-4bb0-8d23-416bbb421cf9.jpg" alt="ishandeveloper">
</div>
</a>
<a href="proxy.php?url=/ishandeveloper/intro-to-linux-for-beginners-g6l" class="ltag__link__link">
<div class="ltag__link__content">
<h2>Intro To Linux [For Beginners]</h2>
<h3>Ishan Sharma γ» Jul 9 '20</h3>
<div class="ltag__link__taglist">
<span class="ltag__link__tag">#linux</span>
<span class="ltag__link__tag">#beginners</span>
<span class="ltag__link__tag">#productivity</span>
<span class="ltag__link__tag">#bash</span>
</div>
</div>
</a>
</div>
<h4>
That's all for now, catch you guys in the next one ππ».
</h4>
<p>Originally published on my <a href="proxy.php?url=//blog.ishandeveloper.com/react-intro">personal blog</a>.</p>
reactbeginnersproductivityjavascriptFlutter APK Generator ActionIshan SharmaThu, 10 Sep 2020 21:11:42 +0000
https://dev.to/ishandeveloper/flutter-apk-generator-action-ehe
https://dev.to/ishandeveloper/flutter-apk-generator-action-ehe<h3>
My Workflow
</h3>
<p>I have made a GitHub Action named 'APK Generator' for flutter projects to help in generating a new apk and pushing it to the repository, whenever changes are made in master branch.</p>
<p>With ease:</p>
<ul>
<li>Generate new release apk's whenever changes are pushed</li>
<li>distribute and test your apps quickly among all collaborators</li>
<li>keep a track of every apk release version.</li>
</ul>
<h3>
Submission Category:
</h3>
<p><strong>Maintainer Must-Haves</strong> , <strong>DIY Deployments</strong></p>
<h3>
Yaml File or Link to Code
</h3>
<p>An example workflow to set up your flutter apk generator action quickly.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight yaml"><code><span class="na">jobs</span><span class="pi">:</span>
<span class="na">build</span><span class="pi">:</span>
<span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
<span class="na">steps</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v1</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Setting up Flutter SDK</span>
<span class="na">uses</span><span class="pi">:</span> <span class="s">subosito/flutter-action@v1</span>
<span class="na">with</span><span class="pi">:</span>
<span class="na">channel</span><span class="pi">:</span> <span class="s">stable</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Fetch Packages</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">flutter pub get</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Build APK</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">flutter build apk</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Copy APK To Parent Directory</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">cp ./build/app/outputs/flutter-apk/app-release.apk ./app.apk</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Commit APK</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">git add ./app.apk</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Configure Github</span>
<span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
<span class="s">git config --local user.email "[email protected]"</span>
<span class="s">git config --local user.name "yourusername"</span>
<span class="s">git commit -m "Generated APK" -a</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Push changes</span>
<span class="na">uses</span><span class="pi">:</span> <span class="s">ad-m/github-push-action@master</span>
<span class="na">with</span><span class="pi">:</span>
<span class="na">github_token</span><span class="pi">:</span> <span class="s">${{ secrets.GITHUB_TOKEN }}</span>
</code></pre>
</div>
<div class="ltag-github-readme-tag">
<div class="readme-overview">
<h2>
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--566lAguM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo">
<a href="proxy.php?url=https://github.com/ishandeveloper">
ishandeveloper
</a> / <a href="proxy.php?url=https://github.com/ishandeveloper/flutter-action-example">
flutter-action-example
</a>
</h2>
<h3>
GitHub Action for generating a new apk and pushing it to the repository, whenever changes are made in master branch.
</h3>
</div>
<div class="ltag-github-body">
<div id="readme" class="md">
<p><a rel="noopener noreferrer" href="proxy.php?url=https://github.com/ishandeveloper/flutter-action-example./assets/hero.png"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--zsePjCLy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://github.com/ishandeveloper/flutter-action-example./assets/hero.png"></a></p>
<br>
<h3>
Flutter APK Generator Action</h3>
<p>This repository is dedicated to a GitHub Action for generating a new apk and pushing it to the repository, whenever changes are made in master branch.</p>
<p>With ease:</p>
<ul>
<li>Generate new release apk's whenever changes are pushed</li>
<li>distribute and test your apps quickly among all collaborators</li>
<li>keep a track of every apk release version.</li>
</ul>
<pre>THIS REPOSITORY WAS CREATED AS A PART OF ACTIONS HACKATHON HOSTED BY DEV.TO AND GITHUB
</pre>
<h3>
Usage</h3>
<p>Example Workflow file</p>
<p>An example workflow to set up your flutter apk generator action quickly.</p>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">jobs</span>
<span class="pl-ent">build</span>:
<span class="pl-ent">runs-on</span>: <span class="pl-s">ubuntu-latest</span>
<span class="pl-ent">steps</span>:
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v1</span>
- <span class="pl-ent">name</span>: <span class="pl-s">Setting up Flutter SDK</span>
<span class="pl-ent">uses</span>: <span class="pl-s">subosito/flutter-action@v1</span>
<span class="pl-ent">with</span>:
<span class="pl-ent">channel</span>: <span class="pl-s">stable</span>
- <span class="pl-ent">name</span>: <span class="pl-s">Fetch Packages</span>
<span class="pl-ent">run</span>: <span class="pl-s">flutter pub get</span>
- <span class="pl-ent">name</span>: <span class="pl-s">Build APK</span>
<span class="pl-ent">run</span>: <span class="pl-s">flutter build apk</span>
- <span class="pl-ent">name</span>: <span class="pl-s">Copy APK To Parent Directory</span>
<span class="pl-ent">run</span>: <span class="pl-s">cp ./build/app/outputs/flutter-apk/app-release.apk ./app.apk</span>
- </pre>β¦
</div>
</div>
</div>
<div class="gh-btn-container"><a class="gh-btn" href="proxy.php?url=https://github.com/ishandeveloper/flutter-action-example">View on GitHub</a></div>
</div>
<h3>
Additional Resources / Info
</h3>
<p>This action uses following two open-source actions under the hood to set up things easily.</p>
<div class="ltag-github-readme-tag">
<div class="readme-overview">
<h2>
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--566lAguM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo">
<a href="proxy.php?url=https://github.com/ad-m">
ad-m
</a> / <a href="proxy.php?url=https://github.com/ad-m/github-push-action">
github-push-action
</a>
</h2>
<h3>
GitHub actions to push back to repository eg. updated code
</h3>
</div>
<div class="ltag-github-body">
<div id="readme" class="md">
<h1>
GitHub Action for GitHub Push</h1>
<p>The GitHub Actions for pushing to GitHub repository local changes authorizing using GitHub token.</p>
<p>With ease:</p>
<ul>
<li>update new code placed in the repository, e.g. by running a linter on it,</li>
<li>track changes in script results using Git as archive,</li>
<li>publish page using GitHub-Pages,</li>
<li>mirror changes to a separate repository.</li>
</ul>
<h2>
Usage</h2>
<h3>
Example Workflow file</h3>
<p>An example workflow to authenticate with GitHub Platform and to push the changes to a specified reference, e.g. an already available branch:</p>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">jobs</span>
<span class="pl-ent">build</span>:
<span class="pl-ent">runs-on</span>: <span class="pl-s">ubuntu-latest</span>
<span class="pl-ent">steps</span>:
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v2</span>
<span class="pl-ent">with</span>:
<span class="pl-ent">persist-credentials</span>: <span class="pl-s">false </span><span class="pl-c"><span class="pl-c">#</span> otherwise, the token used is the GITHUB_TOKEN, instead of your personal access token.</span>
<span class="pl-ent">fetch-depth</span>: <span class="pl-c1">0</span> <span class="pl-c"><span class="pl-c">#</span> otherwise, there would be errors pushing refs to the destination repository.</span>
- <span class="pl-ent">name</span>: <span class="pl-s">Create local changes</span>
<span class="pl-ent">run</span>: <span class="pl-s">|</span>
<span class="pl-s"> ...</span>
- <span class="pl-ent">name</span>: <span class="pl-s">Commit files</span>
<span class="pl-ent">run</span>: <span class="pl-s">|</span>
<span class="pl-s"> git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"</span></pre>β¦
</div>
</div>
</div>
<div class="gh-btn-container"><a class="gh-btn" href="proxy.php?url=https://github.com/ad-m/github-push-action">View on GitHub</a></div>
</div>
<div class="ltag-github-readme-tag">
<div class="readme-overview">
<h2>
<img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--566lAguM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo">
<a href="proxy.php?url=https://github.com/subosito">
subosito
</a> / <a href="proxy.php?url=https://github.com/subosito/flutter-action">
flutter-action
</a>
</h2>
<h3>
Flutter environment for use in GitHub Actions. It works on Linux, Windows, and macOS.
</h3>
</div>
<div class="ltag-github-body">
<div id="readme" class="md">
<h1>
flutter-action</h1>
<p>Flutter environment for use in GitHub Actions. It works on Linux, Windows, and macOS.</p>
<h2>
Usage</h2>
<p>Use specific version and channel:</p>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">steps</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v3</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">subosito/flutter-action@v2</span>
<span class="pl-ent">with</span>:
<span class="pl-ent">flutter-version</span>: <span class="pl-s"><span class="pl-pds">'</span>3.0.5<span class="pl-pds">'</span></span>
<span class="pl-ent">channel</span>: <span class="pl-s"><span class="pl-pds">'</span>stable<span class="pl-pds">'</span></span>
- <span class="pl-ent">run</span>: <span class="pl-s">flutter --version</span></pre>
</div>
<p>Use latest release for particular channel:</p>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">steps</span>:
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v3</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">subosito/flutter-action@v2</span>
<span class="pl-ent">with</span>:
<span class="pl-ent">channel</span>: <span class="pl-s"><span class="pl-pds">'</span>stable<span class="pl-pds">'</span></span> <span class="pl-c"><span class="pl-c">#</span> or: 'beta', 'dev' or 'master'</span>
- <span class="pl-ent">run</span>: <span class="pl-s">flutter --version</span></pre>
</div>
<p>Use latest release for particular version and/or channel:</p>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">steps</span>:
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v3</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">subosito/flutter-action@v2</span>
<span class="pl-ent">with</span>:
<span class="pl-ent">flutter-version</span>: <span class="pl-s"><span class="pl-pds">'</span>1.22.x<span class="pl-pds">'</span></span> <span class="pl-c"><span class="pl-c">#</span> or, you can use 1.22</span>
<span class="pl-ent">channel</span>: <span class="pl-s"><span class="pl-pds">'</span>dev<span class="pl-pds">'</span></span>
- <span class="pl-ent">run</span>: <span class="pl-s">flutter --version</span></pre>
</div>
<p>Use particular version on any channel:</p>
<div class="highlight highlight-source-yaml notranslate position-relative overflow-auto js-code-highlight">
<pre><span class="pl-ent">steps</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">actions/checkout@v3</span>
- <span class="pl-ent">uses</span>: <span class="pl-s">subosito/flutter-action@v2</span>
<span class="pl-ent">with</span>:
<span class="pl-ent">flutter-version</span>: <span class="pl-s"><span class="pl-pds">'</span>2.x<span class="pl-pds">'</span></span>
<span class="pl-ent">channel</span>: <span class="pl-s"><span class="pl-pds">'</span>any</span></pre>β¦
</div>
</div>
</div>
<div class="gh-btn-container"><a class="gh-btn" href="proxy.php?url=https://github.com/subosito/flutter-action">View on GitHub</a></div>
</div>
<p>Made with β₯ by <a href="proxy.php?url=https://github.com/ishandeveloper">ishandeveloper</a></p>
actionshackathonfluttergithuntShared Preferences with FlutterIshan SharmaSun, 23 Aug 2020 20:10:33 +0000
https://dev.to/ishandeveloper/shared-preferences-with-flutter-136c
https://dev.to/ishandeveloper/shared-preferences-with-flutter-136c<p>Originally Published On <a href="proxy.php?url=https://blog.ishandeveloper.com">My Personal Blog</a>.<br>
I have been playing with Flutter for almost 7 months now, and I'm enjoying every second of it. The main factor that I love about Flutter is that it enables you to be more creative and bring out that artist in you. As I have mentioned earlier in one of my <a href="proxy.php?url=https://blog.ishandeveloper.com/new-lang-framework">articles</a>, <strong><em>"Programming is all about embracing that artist in you π¨"</em></strong>.</p>
<p>The first tools that allowed me to get a sense of the same were 'HTML & CSS', they gave me the possibility of having this large empty canvas on the web and paint it in whichever way I want, while also giving me the ability to share it with anyone.</p>
<p>For those of you, who don't know what Flutter is, here's a brief introduction</p>
<h2>
What Is Flutter?
</h2>
<p>Flutter is a UI toolkit by <a href="proxy.php?url=https://google.org">Google</a> and the open-source community which allows you to build beautiful, natively compiled applications for mobile, web, and desktop while maintaining a single codebase. </p>
<p><strong>NOTE: If you haven't started out with Flutter yet and are planning to do the same, then this article will not be much beneficial to you</strong></p>
<p>If you'd like to get started with flutter, refer to flutter's <a href="proxy.php?url=https://flutter.dev/docs/get-started">official documentation</a>. It's one of the best documentation, I've ever read.</p>
<p>For those of you, who do know their way around, Let's jump right in.</p>
<h2>
What is Shared Preferences?
</h2>
<p>When you're working on some client apps, you'll often come across situations, where you need to store some data in the persistent storage of devices. For example, let's say you're using some OAuth client for one of your login methods, for that you'll need to store the <strong>access token</strong> on the client's device so that the client does not have to sign in again on relaunching the app.</p>
<p>Shared Preferences is one of the ways to do it. It provides a way of reading and storing such data in a key-value pair. </p>
<p>Please keep in mind that, by default the Flutter SDK does not come with any support for Shared Preferences. Luckily, The Flutter Team has built a package that helps to achieve the same, <a href="proxy.php?url=https://pub.dev/packages/shared_preferences">'shared_preferences'</a>.</p>
<p>Under the hood, it uses <code>NSUserDefaults</code> on iOS and <code>SharedPreferences</code> on Android to do it's magic.</p>
<p>Let's see a quick sample on how to work with the same.</p>
<ol>
<li>
<h4>
Adding <strong>shared_preferences</strong> in pubspec.yaml
</h4>
<pre class="highlight yaml"><code><span class="na">dependencies</span><span class="pi">:</span>
<span class="na">shared_preferences</span><span class="pi">:</span> <span class="s">^0.5.10</span>
</code></pre>
<p>At the time of writing this article, the latest version of the package is <code>0.5.10</code>. You can surely use whichever is latest.</p>
<p>Once you're done with above, just run <code>flutter pub get</code> in your terminal to get the packages.</p>
</li>
<li>
<h4>
Import the package in your dart file
</h4>
<pre class="highlight dart"><code> <span class="kn">import</span> <span class="s">'package:shared_preferences/shared_preferences.dart'</span><span class="o">;</span>
</code></pre>
</li>
<li>
<h4>
Using the package
</h4>
<p>Now, that we've everything set up, let's dive into using it.</p>
<p>Here's is the typical usage of how we can use SharedPreferences to <code>set</code> & <code>get</code> any key-value pair.</p>
<pre class="highlight dart"><code><span class="kd">var</span> <span class="n">sp</span> <span class="o">=</span> <span class="k">await</span> <span class="n">SharedPreferences</span><span class="o">.</span><span class="na">getInstance</span><span class="p">();</span>
<span class="n">sdp</span><span class="o">.</span><span class="na">setString</span><span class="p">(</span><span class="s">'key'</span><span class="p">,</span> <span class="s">'value'</span><span class="p">);</span>
<span class="kd">var</span> <span class="n">saved_val</span> <span class="o">=</span> <span class="n">sp</span><span class="o">.</span><span class="na">getString</span><span class="p">(</span><span class="s">'key'</span><span class="p">);</span>
</code></pre>
<p>But, this can add up to a lot of boilerplate add junk up your project code pretty quickly, plus it's not so easier to maintain a projec with code like this, and can occur to unnecessary debugging.</p>
<p>So, instead of using this and writing so much boilerplate code every time, we can create a helper service that will handle everything related to Shared Preferences.</p>
<pre class="highlight dart"><code><span class="kn">import</span> <span class="s">'package:shared_preferences/shared_preferences.dart'</span><span class="o">;</span>
<span class="kd">class</span> <span class="nc">StorageService</span><span class="p">{</span>
<span class="kd">static</span> <span class="n">StorageService</span> <span class="n">_service</span><span class="p">;</span>
<span class="kd">static</span> <span class="n">SharedPreferences</span> <span class="n">_pref</span><span class="p">;</span>
<span class="kd">static</span> <span class="n">Future</span><span class="p"><</span><span class="n">StorageService</span><span class="p">></span> <span class="n">createInstance</span><span class="p">()</span> <span class="kd">async</span><span class="p">{</span>
<span class="k">if</span><span class="p">(</span><span class="n">_service</span><span class="o">==</span><span class="kc">null</span><span class="p">){</span>
<span class="cm">/* If service is not initialized */</span>
<span class="kd">var</span> <span class="n">_</span><span class="o">=</span> <span class="n">StorageService</span><span class="o">.</span><span class="na">_</span><span class="p">();</span> <span class="c1">//Creates a local instance of service</span>
<span class="cm">/* Creates an instance of Shared Preferences*/</span>
<span class="k">await</span> <span class="n">_</span><span class="o">.</span><span class="na">_getInstance</span><span class="p">();</span>
<span class="n">_service</span> <span class="o">=</span> <span class="n">_</span><span class="p">;</span>
<span class="p">}</span>
<span class="cm">/* If service is already created return that */</span>
<span class="k">return</span> <span class="n">_service</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="n">_getInstance</span><span class="p">()</span> <span class="kd">async</span> <span class="p">{</span>
<span class="n">_pref</span> <span class="o">=</span> <span class="k">await</span> <span class="n">_pref</span><span class="o">.</span><span class="na">getInstance</span><span class="p">();</span>
<span class="p">}</span>
<span class="cm">/* This method accepts a key and returns, it's value*/</span>
<span class="kd">static</span> <span class="kd">dynamic</span> <span class="n">getValueFromKey</span><span class="p">(</span><span class="kt">String</span> <span class="n">key</span><span class="p">){</span>
<span class="k">if</span><span class="p">(</span><span class="n">_pref</span><span class="o">==</span><span class="kc">null</span><span class="p">)</span> <span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
<span class="k">return</span> <span class="n">_pref</span><span class="o">.</span><span class="na">get</span><span class="p">(</span><span class="n">key</span><span class="p">);</span>
<span class="p">}</span>
<span class="cm">/* This method sets a String and returns true, if set succesfully*/</span>
<span class="kd">static</span> <span class="kt">bool</span> <span class="n">setValueAndKey</span><span class="p">(</span><span class="kt">String</span> <span class="n">key</span><span class="p">,</span> <span class="kt">String</span> <span class="n">value</span><span class="p">){</span>
<span class="k">if</span><span class="p">(</span><span class="n">_pref</span><span class="o">==</span><span class="kc">null</span><span class="p">)</span> <span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
<span class="k">return</span> <span class="n">_pref</span><span class="o">.</span><span class="na">setString</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre>
<p>and just like that, we're done with creating a service for our Shared Preferences.</p>
<p>It's actually a good practice to create an instance of this service, before we run our app. Doing this is pretty simple and straight-forward.</p>
<p>In our <strong>main.dart</strong> file, Let's convert our main function to async<br>
</p>
<pre class="highlight dart"><code><span class="kt">void</span> <span class="nf">main</span><span class="p">()</span> <span class="kd">async</span><span class="p">{</span>
<span class="n">runApp</span><span class="p">(</span><span class="n">myApp</span><span class="p">);</span>
<span class="cm">/*Just make sure to add this line*/</span>
<span class="k">await</span> <span class="n">StorageService</span><span class="o">.</span><span class="na">createInstance</span><span class="p">();</span>
<span class="p">}</span>
</code></pre>
<p>and that's it. With all that set-up, we can easily use our service to store or read data from the storage.</p>
<p>To set a String in persistent storage, we can use :<br>
</p>
<pre class="highlight dart"><code><span class="n">StorageService</span><span class="o">.</span><span class="na">setValueAndKey</span><span class="p">(</span><span class="s">"access_token"</span><span class="p">,</span> <span class="s">"771jkh21y3ubnm21behd21"</span><span class="p">);</span>
</code></pre>
<p>To retrieve the same, we can use :<br>
</p>
<pre class="highlight dart"><code><span class="n">StorageService</span><span class="o">.</span><span class="na">getValueFromKey</span><span class="p">(</span><span class="s">"access_token"</span><span class="p">);</span>
</code></pre>
</li>
</ol>
<h2>
When To Use Shared Preferences?
</h2>
<p>Now that you've got a basic crux of how easy it is to use Shared Preferences in flutter, the real question arises is how to decide when to use <a href="proxy.php?url=https://pub.dev/packages/shared_preferences">shared_preferences</a> or <a href="proxy.php?url=https://pub.dev/packages/sqflite">sqflite</a> or others.</p>
<p>It all comes down to your problem statement, on what you're looking for. If you're planning to store just some access_token or todo list tasks or maybe user's app preferences such as dark theme etc. Basically, If you're planning to store small values, then Shared Preferences is the optimal solution. We don't usually use <a href="proxy.php?url=https://pub.dev/packages/sqflite">sqflite</a> for storing small values, because then you'll have to write a lengthy boilerplate and supporting classes.</p>
<p>But, please keep in mind that Shared Preferences should not be used as a solution for storing complex relational data on a device.</p>
<p>Let us discuss in the comments, what's your preferred way of storing data in persistent storage in Flutter or React-Native or any other ;)</p>
<h4>
Thatβs all for now, catch you guys in the next one ππ».
</h4>
flutterdatabasedartstorageWINAMP - Flutter CodePen ChallengeIshan SharmaFri, 10 Jul 2020 11:36:13 +0000
https://dev.to/ishandeveloper/winamp-flutter-codepen-challenge-3kdp
https://dev.to/ishandeveloper/winamp-flutter-codepen-challenge-3kdp<p>As you might know, the Flutter CodePen challenge is currently ongoing for this month of July. </p>
<p>For those who don't know,</p>
<blockquote>
<p>The Flutter CodePen challenge is a month-long challenge in July to build user experiences with CodePenβs new Flutter editor.</p>
</blockquote>
<p>You can read more about it <a href="proxy.php?url=https://codepen.io/challenges/2020/july/">here</a>.</p>
<h4>
CODE PEN :
</h4>
<p><a href="proxy.php?url=https://codepen.io/ishandeveloper/pen/WNrzveY">codepen.io/ishandeveloper/pen/WNrzveY</a></p>
<h4>
LIVE WORKING DEMO :
</h4>
<p><a href="proxy.php?url=http://winamp.ishandeveloper.com">winamp.ishandeveloper.com</a></p>
<h4>
SOURCE CODE :
</h4>
<p><a href="proxy.php?url=https://github.com/ishandeveloper/WinAMP_Flutter">github.com/ishandeveloper/WinAMP_Flutter</a></p>
<h3>
QUICK SHOWCASE:
</h3>
<p><code>Note : The GIF might take some time to load.</code></p>
<p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--vN7GQXZS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/az5043ueudikeyzvnh2t.gif" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--vN7GQXZS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/az5043ueudikeyzvnh2t.gif" alt="WinAMP Music GIF" width="800" height="533"></a></p>
<p>This was my first Pen that I've ever created (I have forked a few before) on my own. It's a tribute to the <strong>WinAMP Music Player</strong>.</p>
<p>I originally made this as a part of the <strong>#Hack20</strong> Flutter Hackathon. This project of mine was chosen as one of the <strong>Top 5</strong> submissions this year.</p>
<h2>
Few Hacks
</h2>
<p>I have used a bunch of hacks towards building this project. Mainly, as currently there is no native support for playing audio files in flutter web, I used <code>dart:js</code> package to actually call the custom JavaScript functions using Dart.</p>
<p>All Thanks to this amazing post <a href="proxy.php?url=https://medium.com/flutter-community/flutter-web-audio-player-24bded45b928">here</a>.</p>
<h3>
A Brief Look At The Widget Tree
</h3>
<p>I have tried to make it as modular as possible by using a lot of widgets, and would be honest the code is somewhat messy, because I had to create all this in less than 8 hours.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code> MaterialApp
βββ LayoutBuilder
βββ UI
βββ Scaffold
βββ Navbar
βββ Main (Column)
βββ Row
βββ SidebarText
βββ MusicInfoWidget
βββ TrackName
βββ MiniScrollControls
βββ MonoStereoButtons
βββ Row
βββ Column
βββ Seekbar
βββ Controls
</code></pre>
</div>
<h2>
Inspiration Behind This
</h2>
<p>Almost a decade ago, most of us used Winamp for listening to music on our PC devices. It was one of the first music player apps, that was compatible with most modern file types mp3, mp4, avi etc and it featured a wide variety of amazing skins, along with a radio and a browser.</p>
<p>This is just a small attempt to recreate that same experience using <a href="proxy.php?url=https://codepen.io/flutter">@flutter</a> .</p>
<h3>
CodePen
</h3>
<p>Here's the actual codepen. If any bottom overflow occurs, please switch to full view.<br>
<iframe height="600" src="proxy.php?url=https://codepen.io/ishandeveloper/embed/WNrzveY?height=600&default-tab=result&embed-version=2">
</iframe>
</p>
<p>Keep Fluttering π</p>
<h4>
Catch you guys in the next one. π€π»
</h4>
flutterchallengecodepenflutterchallengeIntro To Linux [For Beginners]Ishan SharmaThu, 09 Jul 2020 14:38:53 +0000
https://dev.to/ishandeveloper/intro-to-linux-for-beginners-g6l
https://dev.to/ishandeveloper/intro-to-linux-for-beginners-g6l<p>One of the most important tools for a programmer is the <strong>Operating System</strong>, it runs your whole device and it's important to choose the one that suits you the best!</p>
<p>In this post, I'll be sharing why Linux could be the best choice for your 'Developer' workflow.</p>
<p><strong>Have never heard about Linux ?</strong> Don't worry, I'll explain everything. But first, allow me to share a quick <strong>fact</strong> with you, whether you know it or not,<br>
<br></p>
<h1>
YOU USE LINUX EVERYDAY.
</h1>
<p><br><br>
Yes, you read that correct. Over <strong>850,000</strong> Android Phones running Linux are activated every single day. Meaning, about <strong>100 devices came online, since you started reading this article π</strong>. Nearly <strong>700,000</strong> Televisions running Linux are sold every day. 8 out of 10 <strong>Financial Trades</strong> are powered by Linux. 9 out of 10 <strong>World's Supercomputers</strong> run Linux. Most of the <strong>websites you visit</strong> (Even this!) are powered by Linux. Hell, even most of the <strong>Satellites</strong> in the space, are powered by Linux!</p>
<h4>
That's the sheer scale, versatility & power of Linux!
</h4>
<p>and that is also one of the most important reasons that you should learn to use Linux, using Linux you'll be able to command such a huge variety of devices.</p>
<p>Let's get started.</p>
<h2>
What Is Linux?
</h2>
<p>Linux is actually a kernel.</p>
<p>The Linux kernel is the main component of a Linux operating system (OS) and is the core interface between a computerβs hardware and its processes. It communicates between the two, managing resources as efficiently as possible.</p>
<p>The Linux kernel is world's largest open source project in the computing history! It's available <a href="proxy.php?url=https://github.com/torvalds/linux" rel="noopener noreferrer">here</a>.</p>
<p>Many Operating systems are based on this including Ubuntu, Kubuntu, Debian, Fedora, PopOS, Kali Linux etc. These are called Linux distributions.</p>
<p>When someone says to you that they use linux, what they actually mean is that they use some distribution of Linux.</p>
<p>I hope this is insightful and encourages someone else to make the jump into Linux for doing development work, I have enjoyed the OS so much that I'm actually taking courses on Linux administration and working on becoming a power user. Something I never felt inspired to do on Windows.</p>
<h2>
What's So Special About Linux?
</h2>
<ol>
<li>Open source.</li>
<li>Flexibility</li>
<li>It's Free.</li>
<li>High Security.</li>
<li>Highly Customizable.</li>
</ol>
<h3>
1. Open Source
</h3>
<p>Linux is great for the open-source benefits, which encompass not only the freedom of the software but also that a lot of the open-source projects do not track and sell user data like closed-source projects have been known to do. The customization of Linux is a second-tier factor, but still super imperative for users like you and I. I love to be able to use different shells, the package management solutions, the wide array of software to choose from, and the community support offered by the service. With Windows 10, so many trackers come on the system now, I would say privacy is a big win for Linux right now.</p>
<h3>
2. Flexibility
</h3>
<p>Linux is flexible. Linux is used in a lot of different types of computers. From smart toasters and refrigerators, IOT devices, internet routers, Android smartphones to satellites in the space. You can install Linux on your laptop or desktop today and be up and running with little set up! This flexibility is possible because a Linux operating system is designed to be the sum of many different tools that do one job and do it well. You could piece together a version of Linux that works for your device and is optimized for your needs.</p>
<h3>
3. It's Free
</h3>
<p>Linux is free. Free in multiple ways, you don't need to pay to use Linux and you're free to view, edit, and distribute the source code. When you buy a computer with Windows or mac-OS, the cost of creating and maintaining these operating systems is included in the price.</p>
<h3>
4. High Security
</h3>
<p>Linux is an open operating system, the codes which can be read by everyone. So there are far better chances that when thousands of contributors are collaborating over the same software, it is less probable for any bug or security loopholes to exist, even if they do, they'll usually be fixed in a short amount of time. Also, the ground up design of the Linux distributions is made to be redundant, users have a lower access rights, and, theoretically, even if a virus gets installed, the virus can only access local files and folders, and the system will remain safe.</p>
<h3>
5. Customization
</h3>
<p>If you know your way around the Linux system and you can customize every single corner of it, the whole project code is open-source, therefore you can modify the code to customize the OS and even distribute it as a distribution of your own.</p>
<h2>
So, Which one should I choose?
</h2>
<p>There are <strong>hundreds</strong> of Linux distributions to choose from.\</p>
<p>As the kernel is open source, it allows basically anyone to use it and build their own custom operating system. According to Wikipedia, there are <strong>over 600 Linux Distributions</strong>, you can check the facts <a href="proxy.php?url=https://en.wikipedia.org/wiki/Linux_distribution#:~:text=Almost%20six%20hundred%20Linux%20distributions,of%20those%20in%20active%20development." rel="noopener noreferrer">here</a>.</p>
<p>But for the general usage, <strong>Ubuntu, Fedora, Debian</strong> are much popular. For penetration testing, <strong>Kali Linux</strong> is a popular choice and also <strong>CentOS</strong> for enterprise grade.</p>
<p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F7gw1mvajmv4bwyzhiy6l.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F7gw1mvajmv4bwyzhiy6l.png" alt="Linux Distributions"></a></p>
<p>Each of these distributions have their own strengths & weaknesses, so before switching to a distribution, do check out some sources about which one to choose. If you're absolute beginner, my personal recommendation would be using <strong>Ubuntu</strong>.</p>
<h2>
Basic Linux Commands
</h2>
<p>Now that you know what Linux is, why you should consider using it and once you've chosen a Distribution, it's time to dig into the actual OS.</p>
<p>Let's see some basic commands in Linux.</p>
<p><code>NOTE : Linux commands are case sensitive hence you need to be careful about what you are typing.</code></p>
<p><code>1.</code> <strong>ls</strong> command<br><br>
It refers to List directory contents. If you know windows you <br>
would know that the command dir is used to list the contents in <br>
a directory. In Linux, the ls command is used to list out files <br>
and directories.</p>
<p><code>ls -l</code> helps to paginate the output so you can view page by <br>
page. Otherwise the listing scrolls down rapidly.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">ls</span> <span class="nt">-l</span> filename|foldername
</code></pre>
</div>
<p><code>2.</code> <strong>cd</strong> command<br><br>
It helps to change the current directory. In linux, forward slash is used to denote the contents of a directory.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">cd</span> /etc/
</code></pre>
</div>
<p><code>3.</code> <strong>grep</strong> command<br><br>
It is used to find text in a file. The grep command searches through many files at a time to find a piece of text you are looking for.</p>
<p>The below command will find all of the words in the linux.txt file that matched the word βishandeveloperβ.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">grep</span> <span class="s1">'ishandeveloper'</span> linux.txt
</code></pre>
</div>
<p>It's syntax is : <strong>grep PATTERN [FILE]</strong>.</p>
<p><code>4.</code> <strong>sudo/su</strong> command<br><br>
There are some commands that need elevated rights to run on a Linux system. So you run them as a System Administrator which normal users cannot do.</p>
<p>su command changes the shell to be used as a super user and until you use the exit command you can continue to be the super user</p>
<p>sudo β if you just need to run something as a super user once, you can use the sudo command instead.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">sudo </span>shutdown 5
</code></pre>
</div>
<p><code>5.</code> <strong>pwd</strong> command<br><br>
To identify the directory you are working in you can use the pwd command.<br>
It displays the current working directory path and is useful when directory changes are often<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">pwd</span>
</code></pre>
</div>
<p><code>6.</code> <strong>touch</strong> command<br><br>
It is used to create a new empty file in the existing directory.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">touch </span>old.txt
</code></pre>
</div>
<p>It's syntax is : <strong>touch [FileName]</strong>.<br><br>
You'll notice that a new file 'old.txt' will be created in the current directory.</p>
<p><code>7.</code> <strong>mv</strong> move command<br><br>
It is used to move a file or rename a file.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">mv </span>old.txt new.txt
</code></pre>
</div>
<p><code>8.</code> <strong>cp</strong> copy command<br><br>
It is used to make a copy of an existing file, with a new name in the same directory or similar name in another directory.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">cp </span>new.txt newest.txt
</code></pre>
</div>
<p>It's syntax is : <strong>cp [SOURCEFILE]Β Β [DESTINATIONFILE]</strong>.</p>
<p><code>9.</code> <strong>rm</strong> command<br><br>
This command is used to remove files in a directory or the directory itself. A directory cannot be removed if it is not empty.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">rm </span>file.txt
<span class="nb">rm</span> <span class="nt">-r</span> directory
</code></pre>
</div>
<p>rm βr removes all the contents in a directory and the directory as well.<br><br>
It's syntax is : <strong>rm [name of the file]</strong></p>
<p><code>10.</code> <strong>mkdir</strong> command<br><br>
It is used to create a new directory/folder in the current location<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">mkdir </span>newFolder
</code></pre>
</div>
<p>It's syntax is : <strong>mkdir [directory name]</strong></p>
<p><code>11.</code> <strong>chmod</strong> command [Thanks to <a class="mentioned-user" href="proxy.php?url=https://dev.to/kailyons">@kailyons</a>]<br>
It is used to change the mode of a file system object. Files can have r β read, w- write and x-execute permissions.</p>
<p>It is fairly easy to change the permissions of a file for a quick edit. All you need to do is <code>chmod +/-<permission_char></code></p>
<p>To gain executable permissions for a script file you can use :<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">chmod</span> +x script.sh
</code></pre>
</div>
<p>To remove those permissions for a script file you can use :<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">chmod</span> <span class="nt">-x</span> script.sh
</code></pre>
</div>
<p>You can refer to <a href="proxy.php?url=https://chmod-calculator.com/" rel="noopener noreferrer">this</a>, to learn more about the permission codes in Linux.</p>
<p><code>12.</code> <strong>apt βget</strong> command<br>
apt -get is actually a very powerful and free front-end package manager. It is used to install new software packages, remove available software packages, upgrade existing software packages as well as upgrade the entire operating system. Here, apt β stands for advanced packaging tool.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight shell"><code> <span class="nb">sudo </span>apt-get update
</code></pre>
</div>
<p>The above command will update all the packages currently installed on your system.</p>
<p>Linux doesnβt end here. There are several other amazing features including ssh or others, which just can't be covered in a single post. You can learn more about it by reading articles, documentation or explore them on your own by using Linux in your daily life.</p>
<h4>
That's all for now, catch you guys in the next one ππ».
</h4>
<p>Originally Published on my <a href="proxy.php?url=https://blog.ishandeveloper.com/linux-intro" rel="noopener noreferrer">Personal Blog</a>.</p>
linuxbeginnersproductivitybashA Quick Dive Into ES6Ishan SharmaMon, 06 Jul 2020 17:58:46 +0000
https://dev.to/ishandeveloper/a-quick-dive-into-es6-25b2
https://dev.to/ishandeveloper/a-quick-dive-into-es6-25b2<p>ECMAScript 2015 or ES2015 is a significant update to JavaScript programming language. It is the first major update to the language since ES5 which was standardized in 2009. Therefore, ES2015 is often called <strong>ES6</strong>.</p>
<h2>
What we'll be covering today
</h2>
<ol>
<li>Const, let and var</li>
<li>Default Arguments</li>
<li>Arrow Functions</li>
<li>Template literals</li>
<li>Map, Reduce and Filter</li>
<li>Array and Object Destructuring</li>
<li>Iterables and Loopings</li>
<li>Rest and Spread Operator</li>
<li>Object Literals</li>
<li>Classes in ES6s</li>
<li>Promises</li>
<li>Async and Await</li>
<li>"new" and "this" keyword</li>
</ol>
<h3>
1. Const, let and var
</h3>
<p><strong>1.1 CONST</strong></p>
<ul>
<li>Const defines a constant variable which can't be changed throught the code.</li>
<li>Declaring a variable with const is similar to let when it comes to Block Scope.</li>
</ul>
<p>For example<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">100</span><span class="p">;</span>
<span class="cm">/*
Re-Initializing The Variable.
This will throw an error, as CONST variable can't be changed
*/</span>
<span class="nx">x</span> <span class="o">=</span> <span class="mi">200</span><span class="p">;</span>
<span class="cm">/*
Here 'y' variable is defined in a block.
It can't be accessed outside the scope of this block.
The output of this block would be :
1
*/</span>
<span class="p">{</span>
<span class="kd">const</span> <span class="nx">y</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">y</span><span class="p">);</span>
<span class="p">}</span>
<span class="cm">/*
Will throw an error, CONST y is undefined
*/</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">y</span><span class="p">);</span>
</code></pre>
</div>
<p><strong>1.2 LET</strong></p>
<ul>
<li>"let" defines a variable which can be changed anywhere throught the code.</li>
<li>It can be re-initialised but not re-declared in the same scope.</li>
<li>It has a block scope.
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">100</span><span class="p">;</span>
<span class="cm">/*
Re-Initializing The Variable.
This will update the value of x to 200
*/</span>
<span class="nx">x</span> <span class="o">=</span> <span class="mi">200</span><span class="p">;</span>
<span class="cm">/*
Re-Initializing The Variable in different scopes.
*/</span>
<span class="p">{</span>
<span class="kd">let</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">200</span><span class="p">;</span>
<span class="p">}</span>
<span class="cm">/*
Will display 100 as output
*/</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">x</span><span class="p">);</span>
</code></pre>
</div>
<p><strong>1.3 Var</strong></p>
<ul>
<li>Var keyword is an old method for declaring variables in javascript.</li>
<li>Value of variables declared with var can be changed at any point, during runtime.</li>
<li>Var has only a global scope.</li>
<li>MDN recommends to <strong>not to use</strong> <code>var</code> keyword after release of <code>let</code> and <code>const</code> in ES6.
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">10</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">x</span><span class="p">);</span> <span class="c1">//Returns 20</span>
<span class="p">}</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">x</span><span class="p">);</span> <span class="c1">// Returns 20</span>
</code></pre>
</div>
<h3>
2. Default Arguments
</h3>
<p>Default argument or default parameter allows you to set a default value for your function parameter/argument if <strong>no value</strong> is passed for the same.</p>
<p><strong>Default Argument with ES5</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">product</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">x</span> <span class="o">*</span> <span class="nx">y</span><span class="p">;</span>
<span class="p">}</span>
<span class="cm">/*
Let's just call the function without passing any argument
Output would be : NaN
*/</span>
<span class="nx">product</span><span class="p">();</span>
</code></pre>
</div>
<p><strong>Handling Default Argument with ES5</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">product</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">x</span> <span class="o">=</span> <span class="k">typeof</span> <span class="nx">x</span> <span class="o">!==</span> <span class="dl">"</span><span class="s2">undefined</span><span class="dl">"</span> <span class="p">?</span> <span class="nx">x</span> <span class="p">:</span> <span class="mi">1</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">y</span> <span class="o">=</span> <span class="k">typeof</span> <span class="nx">y</span> <span class="o">!==</span> <span class="dl">"</span><span class="s2">undefined</span><span class="dl">"</span> <span class="p">?</span> <span class="nx">y</span> <span class="p">:</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">return</span> <span class="nx">x</span> <span class="o">*</span> <span class="nx">y</span><span class="p">;</span>
<span class="p">}</span>
<span class="cm">/*
Since we're handling
*/</span>
<span class="nx">product</span><span class="p">();</span>
</code></pre>
</div>
<p>In a case when no parameter is passed, we have to explicitly handle the error by setting default values of a & b. This doesn't look like a good way of handling default arguments.</p>
<p><strong>Handling Default Argument with ES6</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">add</span><span class="p">(</span><span class="nx">a</span> <span class="o">=</span> <span class="mi">5</span><span class="p">,</span> <span class="nx">b</span> <span class="o">=</span> <span class="mi">10</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">a</span> <span class="o">+</span> <span class="nx">b</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">add</span><span class="p">();</span> <span class="c1">// a=5, b=10, sum = 15;</span>
<span class="nx">add</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">);</span> <span class="c1">// a=2, b=3, sum = 5;</span>
<span class="nx">add</span><span class="p">(</span><span class="mi">4</span><span class="p">);</span> <span class="c1">// a=4, b=10, sum=14 ;</span>
</code></pre>
</div>
<p>Default value of A and B will be only used when no parameter is passed.</p>
<h3>
3. Arrow Functions
</h3>
<p>An arrow function is a syntactically compact alternative to a regular function expression without its own binding to <code>this</code>, <code>super</code>,</p>
<p><strong>Regular Functions (ES5)</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">multiply</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">x</span> <span class="o">*</span> <span class="nx">y</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">multiply</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">4</span><span class="p">);</span>
</code></pre>
</div>
<p><strong>Arrow Functions (ES6)</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="c1">// Example 1</span>
<span class="kd">const</span> <span class="nx">multiply</span> <span class="o">=</span> <span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">x</span> <span class="o">*</span> <span class="nx">y</span><span class="p">;</span>
<span class="p">};</span>
<span class="nx">multiply</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">4</span><span class="p">);</span>
</code></pre>
</div>
<h3>
4. Template Literals
</h3>
<p>Template literals can contain placeholders. These are indicated by the dollar sign and curly braces. The expressions in the placeholders and the text between the backticks (``) get passed to a function. They are used to concatenate the parts into a single string.</p>
<p>Let's see an example on formatting strings in ES5.</p>
<p>`<code></code>js<br>
# STRING FORMATTING (WITHOUT ES6)</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code>function welcome(name){
const greetings = 'Hello, ' + name + ' What''s up?';
return greetings;
}
greet('Ishan');
</code></pre>
</div>
<p>/*<br>
Will display output as :<br>
Hello, Ishan What's up?<br>
*/<br>
<code></code>`</p>
<p>`<code></code>js<br>
# STRING FORMATTING (WITH ES6)</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code>function welcome(name){
const greetings = `Hello, ${name} What's up?`;
return greetings;
}
greet('Ishan');
</code></pre>
</div>
<p>/*<br>
Will display output as :<br>
Hello, Ishan What's up?<br>
*/</p>
<p><code></code>`</p>
<p>You might be able to clearly reciprocate the main benefits of the latter approach.</p>
<p><strong>RECAP</strong></p>
<ul>
<li>Template Literals are enclosed by back tick(``) instead of single or double quote.</li>
<li>Placeholders can be inserted between template literals. These are indicated by the dollar sign and curly braces.</li>
</ul>
<h3>
5. Map, Reduce and Filter
</h3>
<p>Map, reduce, and filter are all array methods which were introduced in ES6. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function.</p>
<p><strong>Map Method</strong></p>
<p>The <code>map()</code> method is used for creating a new array from an existing one, while passing each element of the array to a function.</p>
<p>For example: Let's say we have a people array that contains multiple persons as object. But, we just need the age of each person.</p>
<p>How can we do that? Here's one<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">people</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Ishan</span><span class="dl">"</span><span class="p">,</span> <span class="na">age</span><span class="p">:</span> <span class="mi">19</span><span class="p">,</span> <span class="na">profession</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Developer</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Rohit</span><span class="dl">"</span><span class="p">,</span> <span class="na">age</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span> <span class="na">profession</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Student</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Bhavesh</span><span class="dl">"</span><span class="p">,</span> <span class="na">age</span><span class="p">:</span> <span class="mi">18</span><span class="p">,</span> <span class="na">profession</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Enterprenuer</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">];</span>
<span class="kd">const</span> <span class="nx">ages</span> <span class="o">=</span> <span class="nx">people</span><span class="p">.</span><span class="nx">map</span><span class="p">((</span><span class="nx">person</span><span class="p">)</span> <span class="o">=></span> <span class="nx">person</span><span class="p">.</span><span class="nx">username</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">ages</span><span class="p">);</span> <span class="c1">// [ 19, 20, 18 ]</span>
</code></pre>
</div>
<p><strong>Filter Method</strong></p>
<p>Filter method take a function parameter which applies on each array element, then whichever element satisfies the parameter condition returns in the new array.</p>
<p>For example: Let's consider that in the above people example, I only want to filter those users, who have an age of greater than 18 years.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">people</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Ishan</span><span class="dl">"</span><span class="p">,</span> <span class="na">age</span><span class="p">:</span> <span class="mi">19</span><span class="p">,</span> <span class="na">profession</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Developer</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Rohit</span><span class="dl">"</span><span class="p">,</span> <span class="na">age</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span> <span class="na">profession</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Student</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Bhavesh</span><span class="dl">"</span><span class="p">,</span> <span class="na">age</span><span class="p">:</span> <span class="mi">18</span><span class="p">,</span> <span class="na">profession</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Enterprenuer</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">];</span>
<span class="kd">const</span> <span class="nx">aboveEighteen</span> <span class="o">=</span> <span class="nx">people</span><span class="p">.</span><span class="nx">filter</span><span class="p">((</span><span class="nx">person</span><span class="p">)</span> <span class="o">=></span> <span class="nx">person</span><span class="p">.</span><span class="nx">age</span> <span class="o">></span> <span class="mi">18</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">aboveEighteen</span><span class="p">);</span>
<span class="cm">/* [{ name: "Ishan", age: 19, profession: "Developer" },
{ name: "Rohit", age: 20, profession: "Student" } ] */</span>
</code></pre>
</div>
<p><strong>Reduce Method</strong></p>
<p>The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.</p>
<p>For example : Let's say we just want to find the sum of all numbers in an array<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">numbers</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">];</span>
<span class="c1">// Here prevSum will contain the total sum, upto the previous iterated number.</span>
<span class="kd">const</span> <span class="nx">sum</span> <span class="o">=</span> <span class="nx">numbers</span><span class="p">.</span><span class="nx">reduce</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">prevSum</span><span class="p">,</span> <span class="nx">num</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">prevSum</span> <span class="o">+</span> <span class="nx">num</span><span class="p">;</span>
<span class="p">},</span> <span class="mi">0</span><span class="p">);</span>
<span class="c1">// Here '0' indicates the initial value of sum, before reducer function is exectued.</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">sum</span><span class="p">);</span> <span class="c1">// 28</span>
</code></pre>
</div>
<h3>
6. Array and Object Destructuring
</h3>
<p>Destructuring in JavaScript is a simplified method of extracting multiple properties from an array by taking the structure and deconstructing it down into its own constituent parts. It helps in improving the readability and performance of our code.</p>
<p><strong>Destructuring in ES5</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code>
<span class="c1">// Object Destructuring</span>
<span class="kd">var</span> <span class="nx">person</span> <span class="o">=</span> <span class="p">{</span>
<span class="na">name</span> <span class="p">:</span> <span class="dl">'</span><span class="s1">Ishan</span><span class="dl">'</span><span class="p">,</span>
<span class="na">age</span> <span class="p">:</span> <span class="mi">19</span><span class="dl">'</span><span class="s1">,
profession : </span><span class="dl">'</span><span class="nx">Developer</span><span class="dl">'</span><span class="s1">
}
const name = person.name; // Deepak
const age = person.age; // dipakkr
const profession = person.profession // 12345
// Array Destructuring
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"];
const day1 = days[0];
const day2 = days[1];
const day3 = days[2];
</span></code></pre>
</div>
<p><strong>Destructuring in ES6</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="c1">// Object Destructuring</span>
<span class="kd">var</span> <span class="nx">person</span> <span class="o">=</span> <span class="p">{</span>
<span class="na">name</span> <span class="p">:</span> <span class="dl">'</span><span class="s1">Ishan</span><span class="dl">'</span><span class="p">,</span>
<span class="na">age</span> <span class="p">:</span> <span class="mi">19</span><span class="dl">'</span><span class="s1">,
profession : </span><span class="dl">'</span><span class="nx">Developer</span><span class="dl">'</span><span class="s1">
}
const { name, age, profession } = person;
console.log(name);
console.log(age);
console.log(profession);
// Array Destructing
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"];
const [day1, day2, day3] = days;
console.log(day1); // Monday
console.log(day2); // Tuesday
console.log(day3); // Wednesday
</span></code></pre>
</div>
<h3>
7. Iterables and Iterators
</h3>
<p>ES6 introduced a new way to interact with JavaScript data structures β iteration. Here is the list of interable data types in JavaScript.</p>
<div class="table-wrapper-paragraph"><table>
<thead>
<tr>
<th>Iterable</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Array</td>
<td>We can access each individual element by iterating over an array.</td>
</tr>
<tr>
<td>Map</td>
<td>We can iterate over the key-value pair in a list/array.</td>
</tr>
<tr>
<td>Strings</td>
<td>Strings are both iterable & array like, so we can access each character</td>
</tr>
<tr>
<td>Sets</td>
<td>Collections of values that we can iterate through elements</td>
</tr>
</tbody>
</table></div>
<p>Please note that plain objects are not iterable.</p>
<p><code>for...of</code> is a new feature in ES6 that can be helpful in accessing the interables element more easily. The <strong><em>for...of</em></strong> statement simply creates a loop iterating over iterable objects. For example,</p>
<p><strong>Iterating using <code>for...of</code></strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">array</span> <span class="o">=</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">20</span><span class="p">];</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">item</span> <span class="k">of</span> <span class="nx">array</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">item</span><span class="p">);</span>
<span class="p">}</span>
</code></pre>
</div>
<p><strong>Iterating without using <code>for...of</code></strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">array</span> <span class="o">=</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">20</span><span class="p">];</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">item</span> <span class="k">in</span> <span class="nx">array</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">array</span><span class="p">[</span><span class="nx">item</span><span class="p">]);</span>
<span class="p">}</span>
</code></pre>
</div>
<p>As clearly depicted above, in the latter case we can access interable elements directly with for...of method more easily.</p>
<h3>
8. Spread and Rest Operator
</h3>
<p>Spread and Rest Operators are denoted by <code>...</code> three dots. These three dots can either be used as <code>Rest Parameter</code> or <code>Spread Operator</code>.</p>
<p><strong>Rest Parameter</strong><br><br>
It simply collects all the remaning arguments into an array and pass them one by one. Hence, allowing a function to be called with any number of arguments, no matter how it is defined.</p>
<p><strong>Without Using Rest Parameter</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="c1">// Function to print sum of numbers.</span>
<span class="kd">function</span> <span class="nx">addition</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">sum</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</span> <span class="nx">arguments</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">sum</span> <span class="o">=</span> <span class="nx">sum</span> <span class="o">+</span> <span class="nx">arguments</span><span class="p">[</span><span class="nx">i</span><span class="p">];</span>
<span class="p">}</span>
<span class="k">return</span> <span class="nx">sum</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">addition</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">));</span> <span class="c1">// 45</span>
</code></pre>
</div>
<p>Here <code>arguments</code> is a special array-like object that contains all arguments by their index.</p>
<p><strong>Using Rest Paramter</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">addition</span><span class="p">(...</span><span class="nx">numbers</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">sum</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">i</span> <span class="k">of</span> <span class="nx">numbers</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">sum</span> <span class="o">+=</span> <span class="nx">i</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">return</span> <span class="nx">sum</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">addition</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">));</span> <span class="c1">// 45</span>
</code></pre>
</div>
<p><strong>Spread Operator</strong></p>
<ul>
<li>Using the spread operator, we can expand array/object/string into a single list or other element.</li>
<li>Spread operator is exactly the reverse of Rest operator, instead of collecting arguments into an array, it expands an array's elements.</li>
</ul>
<p>For example<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="cm">/*
Let's say we want to find the maximum number in two arrays using the
inbuilt Math.max() function
Note that Math.max() function expects a list of numeric arguments, not a single array.
*/</span>
<span class="kd">let</span> <span class="nx">arr1</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">];</span>
<span class="kd">let</span> <span class="nx">arr2</span> <span class="o">=</span> <span class="p">[</span><span class="mi">8</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="o">-</span><span class="mi">8</span><span class="p">,</span> <span class="mi">1</span><span class="p">];</span>
<span class="nx">alert</span><span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">max</span><span class="p">(...</span><span class="nx">arr1</span><span class="p">,</span> <span class="p">...</span><span class="nx">arr2</span><span class="p">));</span> <span class="c1">// 8</span>
</code></pre>
</div>
<h3>
9. <strong>Object Literals</strong>
</h3>
<p>Object literals are used to create an object in javascript.</p>
<ul>
<li>Object can be initialised by directly using the variable name. See Example 1 below.</li>
<li>Object's method in ES5 require <code>function</code> statement. This is no longer required in ES6, you can directly return statement. See Example 2 below.</li>
<li>Object literals key in ES6 can be dynamic. Any Express can be used to create a key.</li>
</ul>
<p>Let's see object literals in action, through an example.</p>
<p><strong>Object Literals with ES6</strong><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">username</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">ishandeveloper</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">name</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Ishan</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">password</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">SecretNuclearLaunchCode</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">githubID</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">https://github.com/ishandeveloper</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">person</span> <span class="o">=</span> <span class="p">{</span>
<span class="nx">username</span><span class="p">,</span>
<span class="nx">name</span><span class="p">,</span>
<span class="nx">password</span><span class="p">,</span>
<span class="nx">githubID</span><span class="p">,</span>
<span class="p">};</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">person</span><span class="p">.</span><span class="nx">username</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">person</span><span class="p">.</span><span class="nx">githubID</span><span class="p">);</span>
</code></pre>
</div>
<h3>
10. <strong>Classes in ES6</strong>
</h3>
<p>Classes support prototype-based inheritance, constructors, super calls, instance and static methods</p>
<p>There are two ways to define classes in JavaScript.</p>
<ol>
<li>Class Declaration</li>
<li>Class Expression</li>
</ol>
<p><strong>Class Declaration</strong></p>
<p>In order to define class using-declaration method you need to use <code>class</code> keyword followed by className. The class name must start with Capital letter.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">class</span> <span class="nx">Rectangle</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">(</span><span class="nx">height</span><span class="p">,</span> <span class="nx">width</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">height</span> <span class="o">=</span> <span class="nx">height</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="nx">width</span> <span class="o">=</span> <span class="nx">width</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre>
</div>
<p><strong>Class Expression</strong></p>
<p>Class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">Rectangle</span> <span class="o">=</span> <span class="kd">class</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">(</span><span class="nx">height</span><span class="p">,</span> <span class="nx">width</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">height</span> <span class="o">=</span> <span class="nx">height</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="nx">width</span> <span class="o">=</span> <span class="nx">width</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">Rectangle</span><span class="p">.</span><span class="nx">name</span><span class="p">);</span>
</code></pre>
</div>
<h3>
11. Promises
</h3>
<p>For supporting asynchronous programming, JavaScript uses a callback. However, the callback implementation has a major problem which is called as <code>Callback hell.</code> Promises come to rescue to solve the problem of callback hell.</p>
<p><strong>Promises</strong> are a pattern that greatly simplifies asynchronous programming by making the code look synchronous and avoid problems associated with callbacks.</p>
<p>A Promise has three states.</p>
<ul>
<li>
<strong>pending</strong>: Initial state, neither fulfilled nor rejected.</li>
<li>
<strong>fulfilled</strong>: It means that the operation completed successfully.</li>
<li>
<strong>rejected</strong>: It means that the operation failed.
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Promise</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">resolve</span><span class="p">,</span> <span class="nx">reject</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">setTimeout</span><span class="p">(()</span> <span class="o">=></span> <span class="nx">resolve</span><span class="p">(</span><span class="dl">"</span><span class="s2">Success ! </span><span class="dl">"</span><span class="p">),</span> <span class="mi">2000</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">promise</span>
<span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">result</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">result</span><span class="p">);</span>
<span class="p">})</span>
<span class="p">.</span><span class="k">catch</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span>
<span class="p">});</span>
<span class="cm">/*
Result
Success !
*/</span>
</code></pre>
</div>
<blockquote>
<p>DISCLAIMER : Some of the examples and explanations above are inspired from different sources, and rephrased to some extent in my own words, that help me understand the concepts better, all the credit belongs to the respective authors.</p>
</blockquote>
<p>Originally published on <a href="proxy.php?url=https://blog.ishandeveloper.com/es6-quickdive">my personal blog</a>.</p>
javascriptbeginnerswebdevdiscussGoogle Foobar 2020Ishan SharmaWed, 24 Jun 2020 04:19:22 +0000
https://dev.to/ishandeveloper/google-foobar-2020-480h
https://dev.to/ishandeveloper/google-foobar-2020-480h<p>Recently, a few weeks ago, I was browsing on the internet and searching for some C++ related concepts and got prompted with a link to the foobar challenge by google. This challenge acts as a recruiting tool for google. This Google foobar site allows access to questions only for people with a invite.</p>
<p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--Pu2wYlpx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2gje82hveeexjkvxtbzm.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--Pu2wYlpx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2gje82hveeexjkvxtbzm.png" alt="Foobar Challenge" width="880" height="100"></a></p>
<p>In this post, I'll write about the challenge, the problems that were posed for me in the challenge and my approach.</p>
<p>The Google Foobar challenge consisted of <strong>5 Levels</strong>.<br><br>
<strong>Level 1</strong> consisted of a single question. Β Β Β Β Β Β Β Β Β Β [48 hours/question]<br><br>
<strong>Level 2</strong> consisted of two questions. Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β [72 hours/question]<br><br>
<strong>Level 3</strong> consisted of three questions. Β Β Β Β Β Β Β Β Β Β Β Β [96 hours/question]<br><br>
<strong>Level 4</strong> consisted of two questions. Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β [15 days/question]<br><br>
Lastly, <strong>Level 5</strong> consisted of one question. Β Β Β Β [24 days/question]</p>
<blockquote>
<h4>
Please Note : The Code Solutions In This Post Are Written Entirely In Python.
</h4>
</blockquote>
<h2>
Level 1
</h2>
<h3>
- Problem a : 'The cake is not a lie!'
</h3>
<p>Commander Lambda has had an incredibly successful week: she completed the first test run of her LAMBCHOP doomsday device, she captured six key members of the Bunny Rebellion, and she beat her personal high score in Tetris. To celebrate, she's ordered cake for everyone - even the lowliest of minions! But competition among minions is fierce, and if you don't cut exactly equal slices of cake for everyone, you'll get in big trouble.</p>
<p>The cake is round, and decorated with M&Ms in a circle around the edge. But while the rest of the cake is uniform, the M&Ms are not: there are multiple colors, and every minion must get exactly the same sequence of M&Ms. Commander Lambda hates waste and will not tolerate any leftovers, so you also want to make sure you can serve the entire cake.</p>
<p>To help you best cut the cake, you have turned the sequence of colors of the M&Ms on the cake into a string: each possible letter (between a and z) corresponds to a unique color, and the sequence of M&Ms is given clockwise (the decorations form a circle around the outer edge of the cake).</p>
<p>Write a function called solution(s) that, given a non-empty string less than 200 characters in length describing the sequence of M&Ms, returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers.</p>
<ul>
<li>
<h5>
Languages
</h5>
<ul>
<li>To provide a Python solution, edit solution.py</li>
<li>To provide a Java solution, edit Solution.java</li>
</ul>
</li>
</ul>
<h5>
β Test Cases
</h5>
<p>Your code should pass the following test cases. Note that it may <br>
also be run against hidden test cases not shown here.</p>
<ul>
<li>Python Cases
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code> Input:
solution.solution("abcabcabcabc")
Output:4
Input:
solution.solution("abccbaabccba")
Output: 2
</code></pre>
</div>
<ul>
<li>Java Cases
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code> Solution.solution("abcabcabcabc")
Output: 4
Input:
Solution.solution("abccbaabccba")
Output: 2
</code></pre>
</div>
<h3>
Approach
</h3>
<p>To solve this, The first thing I did was to visualize the problem, so as to get a better understanding. I just imagined watching a round cake from top view and assigned few letters (a,b,c,d) to different sections of it in a repeating pattern.</p>
<p>Now that we have visualized it. We can easily infer that, basically all we have to do is to look for repeating sub-strings in the string.</p>
<p>Of course, We need to keep important things in mind before we begin actually writing the code, The function would need to return 0 if the cake could not be cut without leftovers or if the string was empty. We need to identify possible M&M patterns from the input string. The pattern surely could not be longer than half the length of the string. We need to check to see if there were remainders when chopping the string with the possible patterns and discard those results.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight python"><code><span class="k">def</span> <span class="nf">substring_check</span><span class="p">(</span><span class="n">length</span><span class="p">,</span> <span class="n">sub_str</span><span class="p">):</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">length</span><span class="o">-</span><span class="mi">1</span><span class="p">):</span>
<span class="k">if</span><span class="p">(</span><span class="n">sub_str</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">==</span> <span class="n">sub_str</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]):</span>
<span class="k">if</span><span class="p">(</span><span class="n">i</span> <span class="o">==</span> <span class="n">length</span><span class="o">-</span><span class="mi">2</span><span class="p">):</span>
<span class="k">return</span> <span class="n">length</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">continue</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">def</span> <span class="nf">solution</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
<span class="n">parts</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1">#Initially, Let's just assume that cake can be divided into just one piece
</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)):</span>
<span class="n">sub_str</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">if</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">%</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">0</span><span class="p">):</span>
<span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">),</span> <span class="n">i</span><span class="p">):</span>
<span class="n">sub_str</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="n">j</span><span class="p">:</span><span class="n">j</span><span class="o">+</span><span class="n">i</span><span class="p">])</span>
<span class="n">parts</span> <span class="o">=</span> <span class="n">substring_check</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">sub_str</span><span class="p">),</span> <span class="n">sub_str</span><span class="p">)</span>
<span class="k">if</span><span class="p">(</span><span class="n">parts</span> <span class="o">!=</span> <span class="mi">1</span><span class="p">):</span>
<span class="k">return</span> <span class="n">parts</span>
<span class="k">return</span> <span class="n">parts</span>
</code></pre>
</div>
<p>and <strong>Voila!</strong> just like that we have completed the first Level of Foobar Challenge!</p>
<h2>
Level 2
</h2>
<h3>
- Problem a : 'Lovely Lucky Lambs'
</h3>
<p>Being a henchman isn't all drudgery. Occasionally, when Commander Lambda is feeling generous, she'll hand out Lucky LAMBs (Lambda's All-purpose Money Bucks). Henchmen can use Lucky LAMBs to buy things like a second pair of socks, a pillow for their bunks, or even a third daily meal!</p>
<p>However, actually passing out LAMBs isn't easy. Each henchman squad has a strict seniority ranking which must be respected - or else the henchmen will revolt and you'll all get demoted back to minions again!</p>
<p>There are 4 key rules which you must follow in order to avoid a revolt:</p>
<ol>
<li>The most junior henchman (with the least seniority) gets exactly 1 LAMB. (There will always be at least 1 henchman on a team.)</li>
<li>A henchman will revolt if the person who ranks immediately above them gets more than double the number of LAMBs they do.</li>
<li>A henchman will revolt if the amount of LAMBs given to their next two subordinates combined is more than the number of LAMBs they get. (Note that the two most junior henchmen won't have two subordinates, so this rule doesn't apply to them. The 2nd most junior henchman would require at least as many LAMBs as the most junior henchman.)</li>
<li>You can always find more henchmen to pay - the Commander has plenty of employees. If there are enough LAMBs left over such that another henchman could be added as the most senior while obeying the other rules, you must always add and pay that henchman.</li>
</ol>
<p>Note that you may not be able to hand out all the LAMBs. A single LAMB cannot be subdivided. That is, all henchmen must get a positive integer number of LAMBs.</p>
<p>Write a function called solution(total_lambs), where total_lambs is the integer number of LAMBs in the handout you are trying to divide. It should return an integer which represents the difference between the minimum and maximum number of henchmen who can share the LAMBs (that is, being as generous as possible to those you pay and as stingy as possible, respectively) while still obeying all of the above rules to avoid a revolt. For instance, if you had 10 LAMBs and were as generous as possible, you could only pay 3 henchmen (1, 2, and 4 LAMBs, in order of ascending seniority), whereas if you were as stingy as possible, you could pay 4 henchmen (1, 1, 2, and 3 LAMBs). Therefore, solution(10) should return 4-3 = 1.</p>
<p>To keep things interesting, Commander Lambda varies the sizes of the Lucky LAMB payouts. You can expect total_lambs to always be a positive integer less than 1 billion (10 ^ 9).</p>
<ul>
<li>
<h5>
Languages
</h5>
<ul>
<li>To provide a Python solution, edit solution.py</li>
<li>To provide a Java solution, edit Solution.java</li>
</ul>
</li>
</ul>
<h5>
β Test Cases
</h5>
<p>Your code should pass the following test cases. Note that it may <br>
also be run against hidden test cases not shown here.</p>
<ul>
<li>Python Cases
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code> Input:
solution.solution(143)
Output:3
Input:
solution.solution(10)
Output: 1
</code></pre>
</div>
<ul>
<li>Java Cases
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code> Solution.solution(143)
Output: 3
Input:
Solution.solution(10)
Output: 1
</code></pre>
</div>
<h3>
Approach
</h3>
<p>At first glance, this question seems a bit tricky. Basically, they are asking the <strong>difference</strong> between no. of <em><strong>Fibonacci numbers whose sum is less than total_lambs</strong></em> and no. of <em><strong>powers of 2 whose sum is less than total_lambs</strong></em> (* a catch in the rule number 4).</p>
<p>Once we grasp the hold of the question, coming up with the solution is pretty easy.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight python"><code><span class="k">def</span> <span class="nf">solution</span><span class="p">(</span><span class="n">total_lambs</span><span class="p">):</span>
<span class="c1"># Your code here
</span> <span class="n">maxlist</span><span class="o">=</span><span class="p">[]</span>
<span class="n">i</span><span class="o">=</span><span class="mi">0</span>
<span class="n">henchmen</span><span class="o">=</span><span class="mi">0</span>
<span class="k">while</span> <span class="n">i</span><span class="o"><=</span> <span class="n">total_lambs</span><span class="p">:</span>
<span class="n">currentvalue</span><span class="o">=</span><span class="mi">2</span><span class="o">**</span><span class="n">i</span>
<span class="n">maxlist</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">currentvalue</span><span class="p">)</span>
<span class="n">henchmen</span><span class="o">=</span><span class="n">henchmen</span> <span class="o">+</span> <span class="n">currentvalue</span>
<span class="k">if</span> <span class="n">henchmen</span> <span class="o">></span> <span class="n">total_lambs</span><span class="p">:</span>
<span class="k">break</span>
<span class="n">i</span><span class="o">=</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span>
<span class="n">lambs</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span>
<span class="n">fibhenchmen</span><span class="o">=</span><span class="mi">2</span>
<span class="n">y</span><span class="o">=</span><span class="mi">2</span>
<span class="k">while</span> <span class="n">y</span><span class="o"><=</span> <span class="n">total_lambs</span><span class="p">:</span>
<span class="n">value</span><span class="o">=</span><span class="n">lambs</span><span class="p">[</span><span class="n">y</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">lambs</span><span class="p">[</span><span class="n">y</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span>
<span class="n">lambs</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="n">fibhenchmen</span><span class="o">=</span><span class="n">fibhenchmen</span> <span class="o">+</span> <span class="nb">int</span><span class="p">(</span><span class="n">lambs</span><span class="p">[</span><span class="n">y</span><span class="p">])</span>
<span class="k">if</span> <span class="n">fibhenchmen</span> <span class="o">></span> <span class="n">total_lambs</span><span class="p">:</span>
<span class="k">break</span>
<span class="n">y</span><span class="o">=</span><span class="n">y</span><span class="o">+</span><span class="mi">1</span>
<span class="n">answer</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">lambs</span><span class="p">)</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">maxlist</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">abs</span><span class="p">(</span><span class="n">answer</span><span class="p">)</span>
</code></pre>
</div>
<h3>
- Problem b : 'Hey! I already did that.'
</h3>
<p>Commander Lambda uses an automated algorithm to assign minions randomly to tasks, in order to keep her minions on their toes. But you've noticed a flaw in the algorithm - it eventually loops back on itself, so that instead of assigning new minions as it iterates, it gets stuck in a cycle of values so that the same minions end up doing the same tasks over and over again. You think proving this to Commander Lambda will help you make a case for your next promotion.</p>
<p>You have worked out that the algorithm has the following process:</p>
<ol>
<li>Start with a random minion ID n, which is a nonnegative integer of length k in base b</li>
<li>Define x and y as integers of length k. x has the digits of n in descending order, and y has the digits of n in ascending order</li>
<li>Define z = x - y. Add leading zeros to z to maintain length k if necessary</li>
<li>Assign n = z to get the next minion ID, and go back to step 2</li>
</ol>
<p>For example, given minion ID n = 1211, k = 4, b = 10, then x = 2111, y = 1112 and z = 2111 - 1112 = 0999. Then the next minion ID will be n = 0999 and the algorithm iterates again: x = 9990, y = 0999 and z = 9990 - 0999 = 8991, and so on.</p>
<p>Depending on the values of n, k (derived from n), and b, at some point the algorithm reaches a cycle, such as by reaching a constant value. For example, starting with n = 210022, k = 6, b = 3, the algorithm will reach the cycle of values [210111, 122221, 102212] and it will stay in this cycle no matter how many times it continues iterating. Starting with n = 1211, the routine will reach the integer 6174, and since 7641 - 1467 is 6174, it will stay as that value no matter how many times it iterates.</p>
<p>Given a minion ID as a string n representing a nonnegative integer of length k in base b, where 2 <= k <= 9 and 2 <= b <= 10, write a function solution(n, b) which returns the length of the ending cycle of the algorithm above starting with n. For instance, in the example above, solution(210022, 3) would return 3, since iterating on 102212 would return to 210111 when done in base 3. If the algorithm reaches a constant, such as 0, then the length is 1.</p>
<ul>
<li>
<h5>
Languages
</h5>
<ul>
<li>To provide a Python solution, edit solution.py</li>
<li>To provide a Java solution, edit Solution.java</li>
</ul>
</li>
</ul>
<h5>
β Test Cases
</h5>
<p>Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here.</p>
<ul>
<li>Python Cases
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code> Input : solution.solution('210022', 3)
Output : 3
Input : solution.solution('1211', 10)
Output : 1
</code></pre>
</div>
<ul>
<li>Java Cases
</li>
</ul>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code> Input : Solution.solution('210022', 3)
Output : 3
Input : Solution.solution('1211', 10)
Output : 1
</code></pre>
</div>
<h3>
Approach
</h3>
<p>This seemed quite difficult to grasp when I first read the question, I just got puzzled with all that '<em>mumble-jumble</em>'. So, I read the problem again, for a few times & then just started coding my way to achieve the desired results, as stated by the algorithm process above.</p>
<p><code>Please note that the functions 'dTob' & 'bTod' actually represent decimal to binary and binary to decimal conversions respectively.</code><br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight python"><code><span class="k">def</span> <span class="nf">dTob</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="n">digits</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">while</span> <span class="n">d</span> <span class="o">></span> <span class="mi">0</span><span class="p">:</span>
<span class="n">digits</span><span class="p">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">d</span> <span class="o">%</span> <span class="n">b</span><span class="p">))</span>
<span class="n">d</span> <span class="o">=</span> <span class="n">d</span> <span class="o">/</span> <span class="n">b</span>
<span class="k">return</span> <span class="s">''</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="n">digits</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">bTod</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">):</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="nb">str</span><span class="p">(</span><span class="n">b</span><span class="p">):</span>
<span class="n">n</span> <span class="o">=</span> <span class="n">c</span> <span class="o">*</span> <span class="n">n</span> <span class="o">+</span> <span class="nb">int</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="k">return</span> <span class="n">n</span>
<span class="k">def</span> <span class="nf">negative</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="k">if</span> <span class="n">b</span><span class="o">==</span><span class="mi">10</span><span class="p">:</span>
<span class="k">return</span> <span class="nb">int</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">-</span> <span class="nb">int</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="n">dx</span><span class="o">=</span><span class="n">bTod</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">b</span><span class="p">)</span>
<span class="n">dy</span><span class="o">=</span><span class="n">bTod</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="n">b</span><span class="p">)</span>
<span class="n">dz</span><span class="o">=</span><span class="n">dx</span><span class="o">-</span><span class="n">dy</span>
<span class="k">return</span> <span class="n">dTob</span><span class="p">(</span><span class="n">dz</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">solution</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="n">arr</span><span class="o">=</span><span class="p">[]</span>
<span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
<span class="n">i</span> <span class="o">=</span> <span class="s">""</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">n</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">))</span>
<span class="n">j</span> <span class="o">=</span> <span class="s">""</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">n</span><span class="p">)))</span>
<span class="n">k</span> <span class="o">=</span> <span class="n">negative</span><span class="p">(</span><span class="n">i</span><span class="p">,</span><span class="n">j</span><span class="p">,</span><span class="n">b</span><span class="p">)</span>
<span class="n">k2</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">k</span><span class="p">))</span>
<span class="n">i2</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">))</span>
<span class="k">if</span> <span class="p">(</span><span class="n">k2</span><span class="p">)</span> <span class="o">!=</span> <span class="n">i2</span><span class="p">:</span>
<span class="n">k</span> <span class="o">=</span> <span class="n">k</span> <span class="o">*</span> <span class="nb">pow</span><span class="p">(</span><span class="mi">10</span> <span class="p">,(</span><span class="n">i2</span><span class="o">-</span><span class="n">k2</span><span class="p">))</span>
<span class="k">for</span> <span class="n">index</span><span class="p">,</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">arr</span><span class="p">):</span>
<span class="k">if</span> <span class="n">item</span> <span class="o">==</span> <span class="n">k</span><span class="p">:</span>
<span class="k">return</span> <span class="n">index</span> <span class="o">+</span> <span class="mi">1</span>
<span class="n">arr</span> <span class="o">=</span> <span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">+</span> <span class="n">arr</span>
<span class="n">n</span> <span class="o">=</span> <span class="n">k</span>
</code></pre>
</div>
<p>With the above problems out of the way, we can actually proceed to much more interesting challenges.</p>
<h2>
Level 3
</h2>
<h3>
- Problem a : 'Fuel Injection Perfection'
</h3>
<p>Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly.</p>
<p>Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time.</p>
<p>The fuel control mechanisms have three operations:</p>
<ol>
<li>Add one fuel pellet</li>
<li>Remove one fuel pellet</li>
<li>Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets)</li>
</ol>
<p>Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits.</p>
<p>For example:<br><br>
solution(4) returns 2: 4 -> 2 -> 1<br><br>
solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1</p>
<ul>
<li>
<h5>
Languages
</h5>
<ul>
<li>To provide a Python solution, edit solution.py</li>
<li>To provide a Java solution, edit Solution.java</li>
</ul>
</li>
</ul>
<h5>
β Test Cases
</h5>
<p>Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here.</p>
<ul>
<li>
<p>Python Cases<br>
</p>
<pre class="highlight plaintext"><code>Input : solution.solution('15')
Output : 5
Input : solution.solution('4')
Output : 2
</code></pre>
</li>
<li>
<p>Java Cases<br>
</p>
<pre class="highlight plaintext"><code>Input : Solution.solution('15')
Output : 5
Input : Solution.solution('4')
Output : 2
</code></pre>
</li>
</ul>
<h3>
Approach
</h3>
<p>I believe this problem statement is quite easy to grasp and doesn't need much explanation, basically we have an input number and we have to change that number to 1, by performing any of the three operations defined above.</p>
<p>We have to return the minimum possible number of operations required to achieve the same.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight python"><code><span class="k">def</span> <span class="nf">solution</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="n">n</span><span class="o">=</span><span class="nb">int</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">steps</span><span class="o">=</span><span class="mi">0</span>
<span class="k">while</span><span class="p">(</span><span class="n">n</span><span class="o">!=</span><span class="mi">1</span><span class="p">):</span>
<span class="c1"># IF EVEN, I CAN DIVIDE IT BY 2
</span> <span class="k">if</span><span class="p">(</span><span class="n">n</span><span class="o">%</span><span class="mi">2</span><span class="o">==</span><span class="mi">0</span><span class="p">):</span>
<span class="n">n</span><span class="o">=</span><span class="n">n</span><span class="o">/</span><span class="mi">2</span>
<span class="c1"># ELSE IF NOT EVEN, I NEED TO EITHER ADD OR DELETE ONE
</span> <span class="c1"># FUEL PALLETE, WHICHEVER EASIER
</span> <span class="k">elif</span><span class="p">((</span><span class="n">n</span><span class="o">==</span><span class="mi">3</span><span class="p">)</span> <span class="ow">or</span> <span class="p">(</span><span class="n">n</span><span class="o">%</span><span class="mi">4</span><span class="o">==</span><span class="mi">1</span><span class="p">)):</span>
<span class="n">n</span><span class="o">-=</span><span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">n</span><span class="o">+=</span><span class="mi">1</span>
<span class="c1">#INCREASE THE NO. OF STEPS
</span> <span class="n">steps</span><span class="o">=</span><span class="n">steps</span><span class="o">+</span><span class="mi">1</span>
<span class="k">return</span> <span class="n">steps</span>
</code></pre>
</div>
<h3>
- Problem b : 'Bomb, Baby!'
</h3>
<p>You're so close to destroying the LAMBCHOP doomsday device you can taste it! But in order to do so, you need to deploy special self-replicating bombs designed for you by the brightest scientists on Bunny Planet. There are two types: Mach bombs (M) and Facula bombs (F). The bombs, once released into the LAMBCHOP's inner workings, will automatically deploy to all the strategic points you've identified and destroy them at the same time.</p>
<p>But there's a few catches. First, the bombs self-replicate via one of two distinct processes:<br>
Every Mach bomb retrieves a sync unit from a Facula bomb; for every Mach bomb, a Facula bomb is created;<br>
Every Facula bomb spontaneously creates a Mach bomb.</p>
<p>For example, if you had 3 Mach bombs and 2 Facula bombs, they could either produce 3 Mach bombs and 5 Facula bombs, or 5 Mach bombs and 2 Facula bombs. The replication process can be changed each cycle.</p>
<p>Second, you need to ensure that you have exactly the right number of Mach and Facula bombs to destroy the LAMBCHOP device. Too few, and the device might survive. Too many, and you might overload the mass capacitors and create a singularity at the heart of the space station - not good!</p>
<p>And finally, you were only able to smuggle one of each type of bomb - one Mach, one Facula - aboard the ship when you arrived, so that's all you have to start with. (Thus it may be impossible to deploy the bombs to destroy the LAMBCHOP, but that's not going to stop you from trying!)</p>
<p>You need to know how many replication cycles (generations) it will take to generate the correct amount of bombs to destroy the LAMBCHOP. Write a function solution(M, F) where M and F are the number of Mach and Facula bombs needed. Return the fewest number of generations (as a string) that need to pass before you'll have the exact number of bombs necessary to destroy the LAMBCHOP, or the string "impossible" if this can't be done! M and F will be string representations of positive integers no larger than 10^50. For example, if M = "2" and F = "1", one generation would need to pass, so the solution would be "1". However, if M = "2" and F = "4", it would not be possible.</p>
<ul>
<li>
<h5>
Languages
</h5>
<ul>
<li>To provide a Python solution, edit solution.py</li>
<li>To provide a Java solution, edit Solution.java</li>
</ul>
</li>
</ul>
<h5>
β Test Cases
</h5>
<p>Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here.</p>
<ul>
<li>
<p>Python Cases<br>
</p>
<pre class="highlight plaintext"><code>Input : solution.solution('2', '1')
Output : 1
Input : solution.solution('4','7')
Output : 4
</code></pre>
</li>
<li>
<p>Java Cases<br>
</p>
<pre class="highlight plaintext"><code>Input : Solution.solution('2', '1')
Output : 1
Input : Solution.solution('4','7')
Output : 4
</code></pre>
</li>
</ul>
<h3>
Approach
</h3>
<p>From the first look, what I can infer is that I basically have to find the number of subtractions that are required to find the Greatest Common Divisor of M & F.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight python"><code><span class="k">def</span> <span class="nf">solution</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">x</span><span class="p">),</span> <span class="nb">int</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="c1"># 'x' is for Mach Bombs
</span> <span class="c1"># 'y' is for Facula Bombs
</span>
<span class="n">cycles</span> <span class="o">=</span> <span class="mi">0</span>
<span class="c1"># Counts the number of replication cycles
</span>
<span class="k">while</span> <span class="p">(</span><span class="n">x</span> <span class="o">!=</span> <span class="mi">1</span> <span class="ow">and</span> <span class="n">y</span> <span class="o">!=</span> <span class="mi">1</span><span class="p">):</span>
<span class="c1"># If number of Mach bombs and Facula bombs are same
</span> <span class="c1"># Then, It is impossible to replicate to the desired
</span> <span class="c1"># Total number of bombs
</span>
<span class="k">if</span> <span class="n">x</span> <span class="o">%</span> <span class="n">y</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="s">"impossible"</span>
<span class="k">else</span><span class="p">:</span>
<span class="c1"># cycles = cycles + 1
</span> <span class="c1"># ABOVE ASSIGNMENT, CAUSES TWO TEST CASES TO FAIL
</span> <span class="c1"># FOR EXAMPLE FOR 7/3 : 2 CYCLES ARE CONSUMED
</span> <span class="n">cycles</span> <span class="o">=</span> <span class="n">cycles</span><span class="o">+</span><span class="nb">int</span><span class="p">(</span><span class="nb">max</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span><span class="o">/</span><span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="o">%</span> <span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">),</span> <span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="n">cycles</span><span class="o">+</span><span class="nb">max</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
</code></pre>
</div>
<h3>
- Problem c : 'Queue To Do'
</h3>
<p>You're almost ready to make your move to destroy the LAMBCHOP doomsday device, but the security checkpoints that guard the underlying systems of the LAMBCHOP are going to be a problem. You were able to take one down without tripping any alarms, which is great! Except that as Commander Lambda's assistant, you've learned that the checkpoints are about to come under automated review, which means that your sabotage will be discovered and your cover blown - unless you can trick the automated review system.</p>
<p>To trick the system, you'll need to write a program to return the same security checksum that the guards would have after they would have checked all the workers through. Fortunately, Commander Lambda's desire for efficiency won't allow for hours-long lines, so the checkpoint guards have found ways to quicken the pass-through rate. Instead of checking each and every worker coming through, the guards instead go over everyone in line while noting their security IDs, then allow the line to fill back up. Once they've done that they go over the line again, this time leaving off the last worker. They continue doing this, leaving off one more worker from the line each time but recording the security IDs of those they do check, until they skip the entire line, at which point they XOR the IDs of all the workers they noted into a checksum and then take off for lunch. Fortunately, the workers' orderly nature causes them to always line up in numerical order without any gaps.</p>
<p>For example, if the first worker in line has ID 0 and the security checkpoint line holds three workers, the process would look like this:</p>
<div class="table-wrapper-paragraph"><table>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>/</th>
</tr>
</thead>
<tbody>
<tr>
<td>3</td>
<td>4</td>
<td>/</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>/</td>
<td>7</td>
<td>8</td>
</tr>
</tbody>
</table></div>
<p>where the guards' XOR (^) checksum is <strong>0^1^2^3^4^6 == 2</strong>.</p>
<p>Likewise, if the first worker has ID 17 and the checkpoint holds four workers, the process would look like:</p>
<div class="table-wrapper-paragraph"><table>
<thead>
<tr>
<th>17</th>
<th>18</th>
<th>19</th>
<th>20</th>
<th>/</th>
</tr>
</thead>
<tbody>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>/</td>
<td>24</td>
</tr>
<tr>
<td>25</td>
<td>26</td>
<td>/</td>
<td>27</td>
<td>28</td>
</tr>
<tr>
<td>29</td>
<td>/</td>
<td>30</td>
<td>31</td>
<td>32</td>
</tr>
</tbody>
</table></div>
<p>which produces the checksum <strong>17^18^19^20^21^22^23^25^26^29 == 14</strong>.</p>
<p>All worker IDs (including the first worker) are between 0 and 2000000000 inclusive, and the checkpoint line will always be at least 1 worker long.</p>
<p>With this information, write a function solution(start, length) that will cover for the missing security checkpoint by outputting the same checksum the guards would normally submit before lunch. You have just enough time to find out the ID of the first worker to be checked (start) and the length of the line (length) before the automatic review occurs, so your program must generate the proper checksum with just those two values.</p>
<ul>
<li>
<h5>
Languages
</h5>
<ul>
<li>To provide a Python solution, edit solution.py</li>
<li>To provide a Java solution, edit Solution.java</li>
</ul>
</li>
</ul>
<h5>
β Test Cases
</h5>
<p>Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here.</p>
<ul>
<li>
<p>Python Cases<br>
</p>
<pre class="highlight plaintext"><code>Input : solution.solution(0, 3)
Output : 2
Input : solution.solution(17, 4)
Output : 14
</code></pre>
</li>
<li>
<p>Java Cases<br>
</p>
<pre class="highlight plaintext"><code>Input : Solution.solution(0, 3)
Output : 2
Input : Solution.solution(17, 4)
Output : 14
</code></pre>
</li>
</ul>
<h3>
Approach
</h3>
<p>From the first look, what I can infer is that I basically have to find the number of subtractions that are required to find the Greatest Common Divisor of M & F.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight python"><code><span class="k">def</span> <span class="nf">solution</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">x</span><span class="p">),</span> <span class="nb">int</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="c1"># 'x' is for Mach Bombs
</span> <span class="c1"># 'y' is for Facula Bombs
</span>
<span class="n">cycles</span> <span class="o">=</span> <span class="mi">0</span>
<span class="c1"># Counts the number of replication cycles
</span>
<span class="k">while</span> <span class="p">(</span><span class="n">x</span> <span class="o">!=</span> <span class="mi">1</span> <span class="ow">and</span> <span class="n">y</span> <span class="o">!=</span> <span class="mi">1</span><span class="p">):</span>
<span class="c1"># If number of Mach bombs and Facula bombs are same
</span> <span class="c1"># Then, It is impossible to replicate to the desired
</span> <span class="c1"># Total number of bombs
</span>
<span class="k">if</span> <span class="n">x</span> <span class="o">%</span> <span class="n">y</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="s">"impossible"</span>
<span class="k">else</span><span class="p">:</span>
<span class="c1"># cycles = cycles + 1
</span> <span class="c1"># ABOVE ASSIGNMENT, CAUSES TWO TEST CASES TO FAIL
</span> <span class="c1"># FOR EXAMPLE FOR 7/3 : 2 CYCLES ARE CONSUMED
</span> <span class="n">cycles</span> <span class="o">=</span> <span class="n">cycles</span><span class="o">+</span><span class="nb">int</span><span class="p">(</span><span class="nb">max</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span><span class="o">/</span><span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="o">%</span> <span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">),</span> <span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="n">cycles</span><span class="o">+</span><span class="nb">max</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
</code></pre>
</div>
<p>and with that out of the way, we have finally now succesfully completed Level 3 of the Foobar Challenge.</p>
<p>Let's get some rest and we'll move to much more interesting & <em>'mind-boggling'</em> challenges in Level 4 & 5, afterwards.</p>
<h3>
To be updated...
</h3>
<p>Originally published on <a href="proxy.php?url=https://blog.ishandeveloper.com/foobar-2020">my personal blog.</a></p>
googlefoobarchallengeprogrammingBuilding a WikiPedia Search Engine App with JSIshan SharmaWed, 17 Jun 2020 17:40:49 +0000
https://dev.to/ishandeveloper/building-a-wikipedia-search-engine-app-with-js-5hef
https://dev.to/ishandeveloper/building-a-wikipedia-search-engine-app-with-js-5hef<p>I honestly believe that the best way to learn any new technology, programming language, is by building something in that language and putting our knowledge to some practical use.</p>
<p>I receive plenty of messages and queries from some of my dearest friends and juniors asking how to start development, and how to put together the skills they've learnt to actually create something.</p>
<p>While, there are many tutorials on the internet, but most of them are not so beginner friendly, they tend to make a lot of assumptions on the reader's part.</p>
<p>I hope to do my fair duty towards my friends and juniors by writing tutorials on this blog to help grasp several concepts in development and get some apps on their portfolio.</p>
<p>So, without further ado, <strong>Let's Jump right, in!</strong></p>
<h2>
<strong>What We're Gonna Build</strong>
</h2>
<p>I will take you through how to build a Wikipedia Search App with JavaScript. This project was listed in one of the challenges at <a href="proxy.php?url=https://www.freecodecamp.org/challenges/build-a-wikipedia-viewer">FreeCodeCamp</a>.</p>
<p>You can actually view a <strong>live version</strong> of the finished project in your browser at,</p>
<blockquote>
<h4>
<a href="proxy.php?url=https://wikisearch.ishandeveloper.com">wikisearch.ishandeveloper.com</a>
</h4>
</blockquote>
<p>This is the practical working of the app, from a user-perspective:</p>
<ol>
<li>User can search for Wikipedia articles in a search box and view the results in the app itself.</li>
<li>User can visit a random Wikipedia article using the random button.</li>
</ol>
<h2>
Pre-Requisites
</h2>
<p>Knowledge of basics of HTML, CSS & JavsScript is required as this tutorial is intended for beginners who want to learn how to create simple web apps using JavaScript.<br><br>
If you've never built any app before, don't worry! We'll get through this, together!</p>
<p>If you get stuck at any point in this tutorial, you can always refer to the project <a href="proxy.php?url=https://github.com/ishandeveloper/wikipedia-search-engine">source code</a> available on GitHub.</p>
<h2>
<strong>Let's Get Started</strong>
</h2>
<p>I have already created a repository with the <a href="proxy.php?url=http://wikisearch.ishandeveloper.com/Starter_Files/Starter_Files.zip">starter files</a> for this project, you can download them, <a href="proxy.php?url=http://wikisearch.ishandeveloper.com/Starter_Files/Starter_Files.zip">here</a> or from the <a href="proxy.php?url=https://github.com/ishandeveloper/wikipedia-search-engine">Github Repository</a>.</p>
<p>These starter files contain the basic markups and stylings for this tutorial. We're gonna concentrate only on seeing how the JavaScript works.</p>
<p>Just to ensure that we're all on the same page, before we start</p>
<ol>
<li>Download the Starter Files, from above.</li>
<li>Open the project in your preferred code editor (I prefer <strong>VSCode</strong>).</li>
<li>Open <strong>index.html</strong> in your browser (or live-server, if you know that sort of thing).</li>
<li>In your code editor, open '<strong><em>main.js</em></strong>' file.</li>
</ol>
<p>In your browser, you should be able to see, a search bar π like this :</p>
<p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--Xb5rseYR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/5mulxsb26rqiij71s30j.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--Xb5rseYR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/5mulxsb26rqiij71s30j.PNG" alt="Wiki-Search-Bar" width="880" height="112"></a></p>
<p>Once that's done. Let's proceed to add functionality to our app.<br>
For the sake of easiness, I'm actually splitting this section into three parts, each part targetting a different objective.</p>
<p><strong>1. Redirecting user to a random article.</strong><br>
<strong>2. Sending/Recieving search query data from <a href="proxy.php?url=https://www.mediawiki.org/wiki/API:Search">Wikipedia API</a> .</strong><br>
<strong>3. Displaying the search query results on our page.</strong></p>
<p>Let's start with the first one, as it is the easiest to implement.</p>
<h3>
<strong>1. Redirecting user to a random article.</strong>
</h3>
<p>Remember? One of the functionalities we wanted to add initially was, <em>'User can visit a random Wikipedia article using the random button'</em>.</p>
<p>It is fairly easy to do so. In the startup files, I have already created a button, which is actually just an icon enclosed within a link, which I styled to look like a button.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight html"><code><span class="nt"><a</span> <span class="na">href=</span><span class="s">""</span> <span class="na">class=</span><span class="s">"icon random-ico"</span><span class="nt">></span>
<span class="nt"><i</span> <span class="na">class=</span><span class="s">"fas fa-random"</span><span class="nt">></i></span>
<span class="nt"></a></span>
</code></pre>
</div>
<p>To achieve this, we can use :</p>
<ul>
<li><code>https://en.wikipedia.org/wiki/Special:Random</code></li>
</ul>
<p>This is a special link, you can try opening it in your browser and you'll be redirected to a random wikipedia article each time. Here's how it can be implemented.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight html"><code><span class="nt"><a</span>
<span class="na">href=</span><span class="s">"https://en.wikipedia.org/wiki/Special:Random"</span>
<span class="na">target=</span><span class="s">"_blank"</span>
<span class="na">rel=</span><span class="s">"noopener noreferrer"</span>
<span class="na">class=</span><span class="s">"icon random-ico"</span>
<span class="nt">></span>
<span class="nt"><i</span> <span class="na">class=</span><span class="s">"fas fa-random"</span><span class="nt">></i></span>
<span class="nt"></a></span>
</code></pre>
</div>
<p>Now, you should be able to click on the random button, which takes you to a random wikipedia article.<strong>Voila! Just like that, our first task is complete!</strong></p>
<p>Here's a <strong>quick breakdown</strong> of the above code,</p>
<ul>
<li>
href attribute refers to the url of the page we're redirecting to.</li>
<li>
target="_blank" helps to ensure that the link always opens in a new tab.</li>
<li>
rel="noopener noreferrer" is actually here to help fix a security vulnerability with 'target=_blank', you can read more on that, <a href="proxy.php?url=https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/">here</a>.</li>
</ul>
<h3>
2. Sending/Recieving search query data from Wikipedia API .
</h3>
<p>Okay, so the first task here would be to actually retrieve the data entered into the search bar by the user. Let's do that.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="c1">// Grab a reference to form element and store it</span>
<span class="kd">const</span> <span class="nx">form</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.search-form</span><span class="dl">"</span><span class="p">);</span>
<span class="c1">// Add an event listener to form submit event</span>
<span class="nx">form</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">submit</span><span class="dl">"</span><span class="p">,</span> <span class="nx">handleSubmit</span><span class="p">);</span>
</code></pre>
</div>
<p>Here's a breakdown:</p>
<ul>
<li>
querySelector() : It returns the first Element within the document that matches the specified selector, <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector">more on MDN docs</a>.</li>
<li>
addEventListener : It takes two arguments: the DOM event we want to listen for and and the function that will run when the event is triggered (in this case, 'submit' is the DOM event & 'handleSubmit' is the function), <a href="proxy.php?url=sets%20up%20a%20function%20that%20will%20be%20called%20whenever%20the%20specified%20event%20is%20delivered%20to%20the%20target.">more on MDN docs</a>.</li>
</ul>
<p>Now, let's move ahead and create <code>handleSubmit()</code> function.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">handleSubmit</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="p">}</span>
</code></pre>
</div>
<p>Here's a breakdown:</p>
<ul>
<li>You may have noticed <code>'e'</code> as the parameter which is the event that triggered the execution of the function.</li>
<li>
e.preventDefault() : By default, the browser has a tendency to refresh the page, whenever a form is submitted. To prevent this, we're using 'preventDefault()' method, <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault">more on MDN docs</a>.</li>
</ul>
<p>Our page doesn't reload on form submission, but our function doesn't do anything, right? Let's fix this.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">handleSubmit</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="kd">let</span> <span class="nx">query</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.search-input</span><span class="dl">"</span><span class="p">).</span><span class="nx">value</span><span class="p">;</span>
<span class="nx">query</span> <span class="o">=</span> <span class="nx">query</span><span class="p">.</span><span class="nx">trim</span><span class="p">();</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">query</span><span class="p">);</span>
<span class="p">}</span>
</code></pre>
</div>
<p>You can press <strong>Ctrl+Shift+J / Cmd+Opt+J</strong> to open <code>console</code> in chrome and should see an output, once you submit a query in the search bar.</p>
<p>With this, almost half of the job for this step is done! Now, all we have to do is to send the search query to the <a href="proxy.php?url=https://www.mediawiki.org/wiki/API:Search">Wikipedia API</a> and fetch the results.</p>
<p>I have already specified the relevant URL parameters, that we'll be using for this tutorial.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code>https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&origin=*&srlimit=25&utf8=&format=json&srsearch=SEARCH_QUERY
</code></pre>
</div>
<h4>
I'll break this down, quickly:
</h4>
<ul>
<li>
&origin=* : It helps us to bypass CORS restrictions, <a href="proxy.php?url=https://www.mediawiki.org/wiki/API:Cross-site_requests">refer here for more</a>.</li>
<li>
&srlimit=25 : It helps to specify how many total pages to return (25 in this case), <a href="proxy.php?url=https://www.mediawiki.org/wiki/API:Search">refer here for more</a>.</li>
<li>
&format=json : It helps to specify that we are expecting a JSON response <a href="proxy.php?url=https://www.mediawiki.org/wiki/API:Search">refer here for more</a>.</li>
<li>
&srsearch= : It will contain user's search query <a href="proxy.php?url=https://www.mediawiki.org/wiki/API:Search">refer here for more</a>.</li>
</ul>
<p>You can refer to <a href="proxy.php?url=https://www.mediawiki.org/wiki/API:Search">this page</a> for more details.</p>
<p>Moving on, we need to make an actual request to Wikipedia and retrieve the results from there. So, let's replace '<strong><code>console.log(query);</code></strong>' with '<strong>getResults(query);</strong>'.</p>
<p>The handleSubmit function should now look like this :<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">handleSubmit</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="kd">let</span> <span class="nx">query</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.search-input</span><span class="dl">"</span><span class="p">).</span><span class="nx">value</span><span class="p">;</span>
<span class="nx">query</span> <span class="o">=</span> <span class="nx">query</span><span class="p">.</span><span class="nx">trim</span><span class="p">();</span>
<span class="nx">getResults</span><span class="p">(</span><span class="nx">query</span><span class="p">);</span>
<span class="p">}</span>
</code></pre>
</div>
<p>Now, let's create this <strong><code>getResults()</code></strong> function and fetch the search results. We'll be using template literals to add user's search query parameter into the API URL, mentioned above.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">getResults</span><span class="p">(</span><span class="nx">query</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">url</span> <span class="o">=</span> <span class="s2">`https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&origin=*&srlimit=25&utf8=&format=json&srsearch=</span><span class="p">${</span><span class="nx">query</span><span class="p">}</span><span class="s2">`</span><span class="p">;</span>
<span class="nx">fetch</span><span class="p">(</span><span class="nx">url</span><span class="p">)</span>
<span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nx">json</span><span class="p">())</span>
<span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">data</span><span class="p">))</span>
<span class="p">.</span><span class="k">catch</span><span class="p">((</span><span class="nx">e</span><span class="p">)</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">`ERROR : </span><span class="p">${</span><span class="nx">e</span><span class="p">}</span><span class="s2">`</span><span class="p">));</span>
<span class="p">}</span>
</code></pre>
</div>
<h4>
Let's break this down:
</h4>
<ul>
<li>Here we're using back ticks (
<code>`</code>
) for storing the api url in a variable, for more on template literals, <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">refer to MDN docs</a>.</li>
<li>
fetch() : This is an inbuilt method, it takes the url as a parameter specifies that we are expecting a JSON response from Wikipedia & returns a <b>Promise</b> Object. <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">more on MDN docs</a>
</li>
<li>The first <code>.then()</code> expression returns another Promise so we call a second <code>.then()</code> on that to handle the JSON data and log it to the console.</li>
<li>
.catch() : is used to catch any errors, that may occur, it'll log an error message to the console if something goes wrong.</li>
</ul>
<p>Try typing into the input field and submit the form. The raw JSON data will be logged to the console. And with this, we have <strong>successfully completed Step 2</strong>.</p>
<h3>
3. Displaying the search query results on our page.
</h3>
<p>This is the final step of the tutorial, we have recieved the input, we have got the results, now all we need to do is to display those results.</p>
<p>If you take a closer look at the RAW JSON data, logged to the console in the previous step. You'll see that the data object consists of several keys.</p>
<p>The key named <strong>'search'</strong> is the only one useful to us for now. We can access it using <code>data.query.search</code>.</p>
<p>Now that we have the search results, let's first modify the getResults function to display results.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">getResults</span><span class="p">(</span><span class="nx">query</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">url</span> <span class="o">=</span> <span class="s2">`https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&origin=*&srlimit=25&utf8=&format=json&srsearch=</span><span class="p">${</span><span class="nx">query</span><span class="p">}</span><span class="s2">`</span><span class="p">;</span>
<span class="nx">fetch</span><span class="p">(</span><span class="nx">url</span><span class="p">)</span>
<span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nx">json</span><span class="p">())</span>
<span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">putResults</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">query</span><span class="p">.</span><span class="nx">search</span><span class="p">);</span>
<span class="p">})</span>
<span class="p">.</span><span class="k">catch</span><span class="p">((</span><span class="nx">e</span><span class="p">)</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">`ERROR : </span><span class="p">${</span><span class="nx">e</span><span class="p">}</span><span class="s2">`</span><span class="p">));</span>
<span class="p">}</span>
</code></pre>
</div>
<p>Now, let's create a new function'<strong>putResults()</strong>' to which will recieve the search data and add display them on our web page.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">putResults</span><span class="p">(</span><span class="nx">sResults</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// Refer to `.results` section</span>
<span class="kd">const</span> <span class="nx">searchResults</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.results</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">searchResults</span><span class="p">.</span><span class="nx">innerHTML</span> <span class="o">=</span> <span class="dl">""</span><span class="p">;</span>
<span class="c1">// Loop over each result</span>
<span class="nx">sResults</span><span class="p">.</span><span class="nx">forEach</span><span class="p">((</span><span class="nx">result</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="c1">//Generate a wikipedia page url for each result</span>
<span class="kd">const</span> <span class="nx">url</span> <span class="o">=</span> <span class="nb">encodeURI</span><span class="p">(</span><span class="s2">`https://en.wikipedia.org/wiki/</span><span class="p">${</span><span class="nx">result</span><span class="p">.</span><span class="nx">title</span><span class="p">}</span><span class="s2">`</span><span class="p">);</span>
<span class="c1">//Insert a result item as a child one by one into the parent conainter</span>
<span class="nx">searchResults</span><span class="p">.</span><span class="nx">insertAdjacentHTML</span><span class="p">(</span>
<span class="dl">"</span><span class="s2">beforeend</span><span class="dl">"</span><span class="p">,</span>
<span class="s2">`<div class="result">
<h3 class="result-title">
<a href="proxy.php?url=</span><span class="p">${</span><span class="nx">url</span><span class="p">}</span><span class="s2">" target="_blank" rel="noopener"></span><span class="p">${</span><span class="nx">result</span><span class="p">.</span><span class="nx">title</span><span class="p">}</span><span class="s2"></a>
</h3>
<span class="result-snippet"></span><span class="p">${</span><span class="nx">result</span><span class="p">.</span><span class="nx">snippet</span><span class="p">}</span><span class="s2"></span><br>
<a href="proxy.php?url=</span><span class="p">${</span><span class="nx">url</span><span class="p">}</span><span class="s2">" class="result-link" target="_blank" rel="noopener"></span><span class="p">${</span><span class="nx">url</span><span class="p">}</span><span class="s2"></a>
</div>`</span>
<span class="p">);</span>
<span class="p">});</span>
<span class="p">}</span>
</code></pre>
</div>
<p>And that's it! Is it? <strong>Wait! Don't just leave yet.</strong> Let's see what is actually happening in the code above.</p>
<p>Here's a quick breakdown :</p>
<ul>
<li>
<p>encodeURI() : Please note that <b>URLs Cannot Contain Spaces</b>. Therefore, this method is necessary as it helps to convert unformatted text (with whitespaces), into encoded text.</p>
<ul>
<li>For example: If I pass a search query for 'Linus Torvalds' as a paramter, encodeURI function will return 'Linus%20Torvalds'. For more, <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI">refer to MDN docs</a>.</li>
</ul>
</li>
<li><p>sResults.forEach() : This method is used to iterate over each item of an array, Please Note that instead of using <b>array.forEach</b>, we can also use <b>array.map()</b>. For more, <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">refer to MDN docs</a>.</p></li>
<li><p>insertAdjacentHTML : It takes two arguments: The position where we want to append the element and a string containing the HTML to insert on the page. For more info, <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML">refer to MDN docs</a>.</p></li>
</ul>
<h3>
<strong>Here's The Complete Code</strong>
</h3>
<p>In case, you need it.<br>
</p>
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">form</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.search-form</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">form</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">submit</span><span class="dl">"</span><span class="p">,</span> <span class="nx">handleSubmit</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">handleSubmit</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="kd">let</span> <span class="nx">query</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.search-input</span><span class="dl">"</span><span class="p">).</span><span class="nx">value</span><span class="p">;</span>
<span class="nx">query</span> <span class="o">=</span> <span class="nx">query</span><span class="p">.</span><span class="nx">trim</span><span class="p">();</span>
<span class="nx">getResults</span><span class="p">(</span><span class="nx">query</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">getResults</span><span class="p">(</span><span class="nx">query</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">url</span> <span class="o">=</span> <span class="s2">`https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&origin=*&srlimit=25&utf8=&format=json&srsearch=</span><span class="p">${</span><span class="nx">query</span><span class="p">}</span><span class="s2">`</span><span class="p">;</span>
<span class="nx">fetch</span><span class="p">(</span><span class="nx">url</span><span class="p">)</span>
<span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="nx">res</span><span class="p">.</span><span class="nx">json</span><span class="p">())</span>
<span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">putResults</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">query</span><span class="p">.</span><span class="nx">search</span><span class="p">);</span>
<span class="p">})</span>
<span class="p">.</span><span class="k">catch</span><span class="p">((</span><span class="nx">e</span><span class="p">)</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">`ERROR : </span><span class="p">${</span><span class="nx">e</span><span class="p">}</span><span class="s2">`</span><span class="p">));</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">putResults</span><span class="p">(</span><span class="nx">sResults</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">searchResults</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.results</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">searchResults</span><span class="p">.</span><span class="nx">innerHTML</span> <span class="o">=</span> <span class="dl">""</span><span class="p">;</span>
<span class="nx">sResults</span><span class="p">.</span><span class="nx">forEach</span><span class="p">((</span><span class="nx">result</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">url</span> <span class="o">=</span> <span class="nb">encodeURI</span><span class="p">(</span><span class="s2">`https://en.wikipedia.org/wiki/</span><span class="p">${</span><span class="nx">result</span><span class="p">.</span><span class="nx">title</span><span class="p">}</span><span class="s2">`</span><span class="p">);</span>
<span class="nx">searchResults</span><span class="p">.</span><span class="nx">insertAdjacentHTML</span><span class="p">(</span>
<span class="dl">"</span><span class="s2">beforeend</span><span class="dl">"</span><span class="p">,</span>
<span class="s2">`<div class="result">
<h3 class="result-title">
<a href="proxy.php?url=</span><span class="p">${</span><span class="nx">url</span><span class="p">}</span><span class="s2">" target="_blank" rel="noopener"></span><span class="p">${</span><span class="nx">result</span><span class="p">.</span><span class="nx">title</span><span class="p">}</span><span class="s2"></a>
</h3>
<span class="result-snippet"></span><span class="p">${</span><span class="nx">result</span><span class="p">.</span><span class="nx">snippet</span><span class="p">}</span><span class="s2"></span><br>
<a href="proxy.php?url=</span><span class="p">${</span><span class="nx">url</span><span class="p">}</span><span class="s2">" class="result-link" target="_blank" rel="noopener"></span><span class="p">${</span><span class="nx">url</span><span class="p">}</span><span class="s2"></a>
</div>`</span>
<span class="p">);</span>
<span class="p">});</span>
<span class="p">}</span>
</code></pre>
</div>
<p>With that, we've reached the end of this tutorial. I hope you enjoyed it π</p>
<p>This was just to give you a brief look into putting together everything you might've learnt about web development into an actual project.</p>
<h3>
If you want to improve this project,
</h3>
<p>Here are some ideas</p>
<ul>
<li>Show a progress indicator while the request is processing.</li>
<li>Add search suggestions in the search bar, when the user is typing.</li>
<li>Display results on more than one page.</li>
</ul>
<p>Originally posted on <a href="proxy.php?url=https://blog.ishandeveloper.com/wiki-search">my personal blog</a></p>
<p>If you'd like to see more quick tutorials such as this, do let me know in the discussions below!</p>
javascriptprojectswebdevtutorial