<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arpan Patel on Medium]]></title>
        <description><![CDATA[Stories by Arpan Patel on Medium]]></description>
        <link>https://medium.com/@patelarpan2010?source=rss-f85c5a3a7dab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hcYfcja4OTNQ_upHjYde3Q.jpeg</url>
            <title>Stories by Arpan Patel on Medium</title>
            <link>https://medium.com/@patelarpan2010?source=rss-f85c5a3a7dab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:24:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patelarpan2010/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom form validation in angular]]></title>
            <link>https://levelup.gitconnected.com/custom-form-validation-in-angular-91c2af5d6e6?source=rss-f85c5a3a7dab------2</link>
            <guid isPermaLink="false">https://medium.com/p/91c2af5d6e6</guid>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[angular-forms]]></category>
            <category><![CDATA[custom-validation]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[custom-validator]]></category>
            <dc:creator><![CDATA[Arpan Patel]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 17:27:34 GMT</pubDate>
            <atom:updated>2021-08-31T17:27:34.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kz77FG4Q5qsjOUMvAS7IeA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@maxcodes">Maxwell Nelson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today we are going to learn about custom form validation in angular.</p><p>Angular has some built-in validators for us, but it’s not sufficient for all our use cases. Sometimes we need to create our own custom validator.</p><h3>Basic Of Custom Validators</h3><p>Here is the basic structure of the custom validation function.</p><pre>export function yourCustomFunctionName(): <strong>ValidatorFn</strong> {<br>  return (control: <strong>AbstractControl</strong> | form: <strong>FormGroup</strong>): <strong>ValidationErrors</strong> | <strong>null</strong> =&gt; {<br>    return condition ? { key: value } : null<br>  }<br>}</pre><p>Here you can see, yourCustomFunctionName is a function that returns the validator function.</p><p>The validator function takes an Angular AbstractControl object if the validation is used at the field level or FormGroup object when used at the form level.</p><p>We will see both types of validation later in this article.</p><p>It will return null If the control value is valid, Or a validation error object If there is an error.</p><h3>Implementing Custom Validators</h3><p>Now you get the basic idea. So without further ado let implement our custom form validation.</p><p>We are going to use the reactive form in this example.</p><pre>&lt;form [formGroup]=&quot;validationForm&quot;&gt;<br>  &lt;div&gt;<br>   &lt;label&gt;Name&lt;/label&gt;<br>   &lt;input formControlName=&quot;name&quot;&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div&gt;<br>   &lt;label&gt;From&lt;/label&gt;<br>   &lt;input type=&quot;number&quot; formControlName=&quot;from&quot;&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div&gt;<br>   &lt;label&gt;To&lt;/label&gt;<br>   &lt;input type=&quot;number&quot; formControlName=&quot;to&quot;&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;&lt;/form&gt;</pre><p>Here we can see the simple form with three fields, one is for name input and the other two are for range input.</p><p>Here is the component class for this template.</p><pre><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br>export class AppComponent   {<br>  <br>  validationForm = this.fb.group({<br>    name: [&#39;&#39;, [Validators.required, <strong>nameValidation()</strong>]],<br>    from: [&#39;&#39;, [Validators.required]],<br>    to: [&#39;&#39;, [Validators.required]]<br>  }, {<br>    validators: [<strong>rangeValidation()</strong>]<br>  });</pre><pre>  constructor(private fb: FormBuilder) {}</pre><pre>  get name() { return this.validationForm.get(&#39;name&#39;); }</pre><pre>}</pre><p>You can see here, That we apply two custom validation. One at the field level (<strong>nameValidation</strong>) and another at the form level (<strong>rangeValidation</strong>).</p><p>You can also notice that we have one get method for our name control. That we use later in the component template to check our validation.</p><p>If you are confused about when to use field-level validation and when to use form level. Then it’s easy, if you want to validate input based on its own value then you can use field-level. But if your validation is based on another field of form then you can use form level validation.</p><p>Let implement these two validations one by one respectively.</p><h4>Field level Custom Validators</h4><p>For sake of this article, we are going to implement very simple validation.</p><p>The name field value always includes the word “<strong>angular</strong>” in it.</p><pre>export function nameValidation(): <strong>ValidatorFn</strong> {</pre><pre>  return (<strong>control: AbstractControl</strong>): ValidationErrors | null =&gt; {</pre><pre>    const isValid = /angular/gm.test(control.value);</pre><pre>    return isValid ? <strong>null</strong> : <strong>{ name: true }</strong>;</pre><pre>  };</pre><pre>}</pre><p>Let’s understand what is going on here. We can see here that our nameValidator() function return ValidatorFn . And It’s not a validator function itself.</p><p>Validator function takes a control object and returns null If the control value is valid, or else returns an ValidationErrors object.</p><h4>Form level Custom Validators</h4><p>Now let’s implement our form-level custom validation function. For that also we are going to implement simple validation.</p><p>Check to value is always greater thanfrom value.</p><pre>export function rangeValidation(): <strong>ValidatorFn</strong> {</pre><pre> return (<strong>form: FormGroup</strong>): ValidationErrors | null =&gt; {</pre><pre>   const from = Number(form.get(&#39;from&#39;)?.value);<br>   const to = Number(form.get(&#39;to&#39;)?.value);<br>   <br>    return  from &gt;= to ? {range: true} : null;</pre><pre>  };</pre><pre>}</pre><p>You can see that the function structure is almost the same as the above function. But the major difference is here validation function take FormGroup object as a parameter.</p><p>Here we check if from value is greater than or equal to to value. It’s a return error object or else returns null.</p><h3>How to display errors in templates?</h3><p>Now we learned how to create our own custom validation. Let’s use this validation in our template.</p><p>For brevity, I’m going to check only our custom validation, Not going to check input touched state.</p><p><strong>Check Field level Custom Validation</strong></p><pre>&lt;div&gt;<br> &lt;label&gt;Name&lt;/label&gt;<br> &lt;input class=&quot;form-control&quot; formControlName=&quot;name&quot;&gt;<br> <strong>&lt;div *ngIf=&quot;name.errors?.name&quot;&gt;Please enter valid name&lt;/div&gt;</strong><br>&lt;/div&gt;</pre><p><strong>Check Form level Custom Validation</strong></p><pre>&lt;div class=&quot;form-group&quot;&gt;<br>&lt;label&gt;To&lt;/label&gt;<br>&lt;input type=&quot;number&quot; class=&quot;form-control&quot; formControlName=&quot;to&quot;&gt;<br><strong>&lt;div *ngIf=&quot;validationForm.errors?.range&quot;&gt;Please enter valid range&lt;/div&gt;</strong><br>&lt;/div&gt;</pre><h3>Play with running app in stackblitz</h3><p><a href="https://stackblitz.com/edit/angular-ivy-2ywlef?embed=1&amp;file=src/app/app.component.ts&amp;hideExplorer=1">Custom Form Validation in Angular - StackBlitz</a></p><h3>Source Code</h3><p><a href="https://github.com/arpanpatel/Custom-Form-Validation-In-Angular">GitHub - arpanpatel/Custom-Form-Validation-In-Angular: Created with StackBlitz ⚡️</a></p><h3><strong>We did it.</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FW0Vz7zDK7vgMBc2fpw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FW0Vz7zDK7vgMBc2fpw%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FW0Vz7zDK7vgMBc2fpw%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/824a5afca50781d94b967630581f7669/href">https://medium.com/media/824a5afca50781d94b967630581f7669/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91c2af5d6e6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/custom-form-validation-in-angular-91c2af5d6e6">Custom form validation in angular</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular lazyload module with a custom network-aware preload strategy.]]></title>
            <link>https://medium.com/@patelarpan2010/angular-lazyload-module-with-custom-network-aware-preload-strategy-2410289382c8?source=rss-f85c5a3a7dab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2410289382c8</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <dc:creator><![CDATA[Arpan Patel]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 14:36:48 GMT</pubDate>
            <atom:updated>2021-08-04T05:41:43.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUDuaWS9F0XqohkJV00yyw.jpeg" /></figure><p>When we start developing an enterprise-level application. By the time our application got bigger, and eventually we end up with a large bundle size. We don’t want to serve this large bundle to our user browser in one go. It makes our application slow and creates a bad user experience.</p><p>To eliminate this problem we arranged our application into multiple feature modules. Although by default modules are eagerly loaded in angular. Which means that as soon as application loads all module is loaded.</p><p>So you need some kind of pattern that loads the module as we needed. We call this pattern lazy loading. According to the angular documentation:</p><blockquote>Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.</blockquote><h4>Implement Lazy Loading</h4><p>So without further ado, let’s start implementing lazyload in our application. You are here so I assumed that you already know how to set up the angular project. So without further ado, let’s start implementing lazyload in our application. You are here so I assumed that you already know how to set up the angular project. So we don’t want to get into it.</p><p>Now let’s create a feature module. Using the following command.</p><pre>ng generate module about --route about --module app.module</pre><p>This command will create <em>about</em> folder. Inside this folder, It will create the following files for us.</p><ol><li>about.module.ts file with AboutModule define inside.</li><li>about-routing.module.ts file with AboutRoutingModule define inside.</li></ol><p>It also creates a component file about.component.ts and automatically declares the AboutComponent in about-routing.module.ts like this.</p><pre>const routes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    component: AboutComponent<br>  }<br>];</pre><p>Because the new module we created is meant for lazyloading. It adds the declared route, about to the routes array declared in the module provided as the --module option. In our case it’s app.module.ts . So it generates the following code in app-routing.module.ts . There no need to says that AppRoutingModule is defined inside AppModule.</p><pre>const routes: Routes = [<br>  {<br>    path: &#39;about&#39;,<br>    loadChildren: () =&gt; import(&#39;./about/about.module&#39;).then(m =&gt; m.AboutModule)<br>  },<br>];</pre><p>Now you know how to create a lazyloaded feature module. Let’s create two more modules for <strong>contact </strong>and <strong>blog </strong>respectively<strong>. </strong>Using following commands.</p><pre>ng generate module contact --route contact --module app.module</pre><p>And</p><pre>ng generate module blog --route blog --module app.module</pre><p>After performing the above commands. Now if you look into your app-routing.module.ts file it looks something like this.</p><pre>const routes: Routes = [<br>  {<br>    path: &#39;about&#39;,<br>    loadChildren: () =&gt; import(&#39;./about/about.module&#39;).then(m =&gt; m.AboutModule)<br>  },<br>  {<br>    path: &#39;contact&#39;,<br>    loadChildren: () =&gt; import(&#39;./contact/contact.module&#39;).then(m =&gt; m.ContactModule)<br>  },<br>  {<br>    path: &#39;blog&#39;,<br>    loadChildren: () =&gt; import(&#39;./blog/blog.module&#39;).then(m =&gt; m.BlogModule)<br>  },<br>];</pre><p>Our lazy-loaded module is ready to use. But there is one thing is remaining, we need to add navigation to load our lazyload feature modules. Replace all content inside app.component.html with the following.</p><pre>&lt;a routerLink=&quot;about&quot;&gt;About&lt;/a&gt;<br>&lt;a routerLink=&quot;contact&quot;&gt;Contact&lt;/a&gt;<br>&lt;a routerLink=&quot;blog&quot;&gt;Blog&lt;/a&gt;</pre><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>Now let’s run our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xqiu6KHXZnloK813hNGQFw.gif" /><figcaption>Angular Application With LazyLoading Module.</figcaption></figure><p>This is will work great. It’s a load module when the user clicks on the link. But can we do better?. Yes, we can.</p><h4>Enter Preloading Strategy</h4><p>Out of the box, Angular default preload strategy is to not preload, So it’s loads the module when the user requests. We can change this behavior by providing a built-in preload strategy. Or We can create our own custom preload strategy.</p><p><strong>Built-in preload strategy</strong></p><ol><li><strong>NoPreloading</strong> (default): As the name suggests no module is preloaded.</li><li><strong>PreloadAllModules</strong>: Which preloads all lazy-loaded routes.</li></ol><p>But we don’t want to go into it today.</p><p><strong>Custom preload strategy</strong></p><p>Today we are going to look into a custom preload strategy. For creating a custom preload strategy we need to implement PreloadingStrategy class.</p><p>PreloadingStrategy is a simple class object implementing a preload method.</p><p>preload method takes two arguments.</p><ol><li>route : route is a route object.</li><li>fn: a function that triggers the loading of a module.</li></ol><p>Now let’s create a service network-aware-preload.service.ts and write the following code (or paste it, that all you are gonna do 😀).</p><pre>import {<strong><em>Injectable</em></strong>} from &#39;@angular/core&#39;;<br>import {<strong>PreloadingStrategy</strong>, Route} from &#39;@angular/router&#39;;<br>import {Observable, of} from &#39;rxjs&#39;;<br><em><br></em>declare const navigator: any;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class NetworkAwarePreloadService implements <strong>PreloadingStrategy</strong> {</pre><pre>  <strong>preload</strong>(route: Route, fn: () =&gt; Observable&lt;any&gt;): Observable&lt;any&gt;    {<br>    const connection = navigator.connection;</pre><pre>    if (connection.saveData) {<br>      return of(null);<br>    }</pre><pre>    const speed = connection.effectiveType;<br>    const slowConnections = [&#39;slow-2g&#39;, &#39;2g&#39;, &#39;3g&#39;];</pre><pre>    if (slowConnections.includes(speed)) {<br>      return of(null);<br>    }</pre><pre>    return fn();<br>  }<br>}</pre><p>Here we are using a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection">navigator.connection</a> to get information about the system’s connection, such as the current bandwidth of the user’s device or whether the connection is metered.</p><p>Here we first check for <strong>saveData </strong>mode<strong>. </strong>If saveData mode is on, Our application disables the preloading of the modules.</p><pre>if (connection.saveData) {<br>   return of(null);<br>}</pre><p>In another condition, we check whether a user connection is <strong>slow-2g, 2g, </strong>or <strong>3g. </strong>If our user is on any of these connections, Our application disables the preloading of the modules.</p><pre>const speed = connection.effectiveType;<br>const slowConnections = [&#39;slow-2g&#39;, &#39;2g&#39;, &#39;3g&#39;];</pre><pre>if (slowConnections.includes(speed)) {<br>   return of(null);<br>}</pre><p>If none of the above conditions matches then preload return a fn() and our application preload modules.</p><p>Now our custom preloading strategy is ready to use. Pass this service into RouterModule router option preloadingStrategy in forRoot function.</p><pre>@NgModule({<br>  imports: [RouterModule.<em>forRoot</em>(<br>    routes,<br>    {<br>      preloadingStrategy: NetworkAwarePreloadService,<br>    }<br>  )],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule {}</pre><p>After this reload your application. If your internet speed is good then, all the modules are preloaded for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVy0zfjVR4EcJAUL_7Qcng.png" /><figcaption>User On fast internet connection</figcaption></figure><p>And if you are on a slow internet connection like <strong>2g</strong> or <strong>3g</strong>. You can see in the below image only the active module is loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFKl_5lzl4kETxxsFGlsgw.png" /><figcaption>the user on slow internet connection</figcaption></figure><p><strong>Source Code</strong></p><p><em>You can find the source code </em><a href="https://github.com/arpanpatel/angular-lazy-loading-feature-modules"><em>on GitHub</em></a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fbg1MQ6IUVoVOM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fbg1MQ6IUVoVOM%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fbg1MQ6IUVoVOM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc54d0c0e3dee023c7fccbd5f4a1f9fe/href">https://medium.com/media/bc54d0c0e3dee023c7fccbd5f4a1f9fe/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2410289382c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Bypass Angular HTTP Interceptor.]]></title>
            <link>https://medium.com/@patelarpan2010/how-to-bypass-angular-http-interceptor-2491afca16a3?source=rss-f85c5a3a7dab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2491afca16a3</guid>
            <category><![CDATA[services]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[interceptors]]></category>
            <dc:creator><![CDATA[Arpan Patel]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 10:50:37 GMT</pubDate>
            <atom:updated>2021-08-02T14:17:43.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZhTP9Dli5_cA6MaJQ3kew.jpeg" /></figure><p>Yes, you heard right sometimes you need to bypass the angular HTTP interceptor for a particular HTTP request.</p><p>Before we move forward, let’s revise what is angular interceptor?. As per documentation.</p><blockquote>With interception, you declare <em>interceptors</em> that inspect and transform HTTP requests from your application to a server. The same interceptors can also inspect and transform a server’s responses on their way back to the application. Multiple interceptors form a <em>forward-and-backward</em> chain of request/response handlers.</blockquote><p>I know very technical. let’s put this in simple words. angular interceptor checks every request you send to the service. and also check responses coming back from the server.</p><p>Here is some use of this interceptor.</p><ul><li>Add a token HTTP requests</li><li>Add custom HTTP header for all HTTP requests</li><li>The logic for custom error handling</li><li>Log all HTTP activity</li></ul><p>I think we get a basic idea of the angular interceptor.</p><p>I know it’s good to use an angular interceptor. but in some cases, we need to bypass it. So here is the solution.</p><h3>Create a new HttpClient</h3><p>Here we create a new HttpClient using <a href="https://angular.io/api/common/http/HttpBackend">HttpBackend</a>. Interceptors sit between the <a href="https://angular.io/api/common/http/HttpClient">HttpClient</a> interface and the <a href="https://angular.io/api/common/http/HttpBackend">HttpBackend</a>. So the trick is we need to inject <a href="https://angular.io/api/common/http/HttpBackend">HttpBackend</a> directly into our service and create a new HttpClient using <a href="https://angular.io/api/common/http/HttpBackend">HttpBackend</a> .</p><p>As per official documentation</p><blockquote>When injected, <a href="https://angular.io/api/common/http/HttpBackend">HttpBackend</a> <strong>dispatches requests directly to the backend</strong>, without going through the interceptor chain.</blockquote><pre>import {HttpBackend, HttpClient} from &#39;@angular/common/http&#39;;<br>import {<strong><em>Injectable</em></strong>} from &#39;@angular/core&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class AdmissionHttpService {</pre><pre>  private httpClient: HttpClient;</pre><pre>  constructor(<br>    private handler: HttpBackend,<br>  ) {<br>    this.httpClient = new HttpClient(handler);<br>  }<br><br><br>  getData() {<br>    return this.httpClient.get(url);<br>  }<br><br>}</pre><p>So that’s all for today. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2491afca16a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Next.js ▲ with styled-components  easy]]></title>
            <link>https://medium.com/@patelarpan2010/using-next-js-with-styled-components-easy-dfff3849e4f1?source=rss-f85c5a3a7dab------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfff3849e4f1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arpan Patel]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 08:37:56 GMT</pubDate>
            <atom:updated>2021-07-31T02:04:56.111Z</atom:updated>
            <content:encoded><![CDATA[<p>When you need a server-side rendering React app. <a href="https://nextjs.org/">Next.js</a> is the best choice. And when it comes to styling react component first thing comes in my mind is <a href="https://www.styled-components.com/">styled-components</a>. Although it depends on your preference.</p><p>Let say you want to pair <a href="https://nextjs.org/">Next.js</a> with <a href="https://www.styled-components.com/">styled-components</a>. But use styled-components with Next.js is not straightforward. It’s a little bit tricky. Let see how we can achieve that.</p><ol><li><a href="https://app.contentful.com/spaces/x2hu75nfw600/entries/2VoqEfclBehJH5eZK6OrnW#1-setup-nextjs-project">Setup Next.js</a></li><li><a href="https://app.contentful.com/spaces/x2hu75nfw600/entries/2VoqEfclBehJH5eZK6OrnW#2-create-our-first-nextjs-page">Create our first Next.js page</a></li><li><a href="https://app.contentful.com/spaces/x2hu75nfw600/entries/2VoqEfclBehJH5eZK6OrnW#3-install-styled-components">Install styled-components</a></li><li><a href="https://app.contentful.com/spaces/x2hu75nfw600/entries/2VoqEfclBehJH5eZK6OrnW#4-install-and-setup-styled-components-babel-plugin">Install and setup styled-components Babel plugin</a></li><li><a href="https://app.contentful.com/spaces/x2hu75nfw600/entries/2VoqEfclBehJH5eZK6OrnW#5-create-custom-_documentjs-file">Create _document.js file</a></li><li><a href="https://app.contentful.com/spaces/x2hu75nfw600/entries/2VoqEfclBehJH5eZK6OrnW#6-result">Result</a></li></ol><h3>1. Setup Next.js project</h3><p>We start by creating a new directory. And cd into this directory.</p><pre>mkdir next-with-styled-component &amp;amp;&amp;amp; cd next-with-styled-component</pre><p>Now we need to create our package.json file. And then run the following command into your terminal.</p><pre>npm init</pre><p>It will create a package.json file. Now we need to install all Next.js related dependencies for our project. Run the following command into your cmd/terminal.</p><pre>npm install --save next react react-dom</pre><p>It will create a node_module folder and install all Next.js related dependencies into it.</p><p>Now open a package.json file into your favorite editor. Add the following content into it.</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;start&quot;: &quot;next start&quot;<br>  }<br>}</pre><h3>2. Create our first Next.js page</h3><p>Create pages directory and create file name index.js under pages directory. Now open index.js the file and paste the following content into it.</p><pre>function Home() {<br>  return &lt;div&gt;Hello world!&lt;/div&gt;;<br>}</pre><pre>export default Home;</pre><p>Now run our first page into the browser using the following command.</p><pre>npm run dev</pre><p>It starts the development server at <a href="http://localhost:3000/">http://localhost:3000</a>.</p><h3>3. Install styled-components</h3><p>Now it&#39;s time to add styled component into our project. You can add styled components using the following command.</p><pre>npm install --save styled-components</pre><h3>4. Install and setup styled-components Babel plugin</h3><p>We also need babel-plugin-styled-components. It helps to consistently hashed component classNames between environments (a must for server-side rendering).</p><p>You can install babel-plugin-styled-components it as a dev dependency using the following command.</p><pre>npm install --save-dev babel-plugin-styled-components</pre><p>Then create a .babelrc file in the root of the project.</p><p>Open .babelrc the file adds the following things.</p><ol><li>Add “next/babel” as preset</li><li>Add a styled-components plugin and set the SSR option to true</li></ol><p>Now your .babelrc the file looks something this.</p><pre>{ <br>  &quot;presets&quot;: [&quot;next/babel&quot;], <br>  &quot;plugins&quot;: [<br>      [&quot;styled-components&quot;, { &quot;ssr&quot;: true }]<br>   ]<br>}</pre><h3>5. Create a custom _document.js file</h3><p>To render our styled-components at the server side we need to override _document.js. for this create a _document.js file under the pages folder. and add the following content into it.</p><pre>import Document from &quot;next/document&quot;;<br>//highlight-next-line<br>import { ServerStyleSheet } from &quot;styled-components&quot;;<br>export default class MyDocument extends Document {<br>  static async getInitialProps(ctx) {<br>    //highlight-next-line<br>    const sheet = new ServerStyleSheet();<br>    const originalRenderPage = ctx.renderPage;<br>    try {<br>      ctx.renderPage = () =&amp;gt;<br>        originalRenderPage({<br>          //highlight-next-line<br>          enhanceApp: App =&amp;gt; props =&amp;gt; sheet.collectStyles()<br>        });<br>      const initialProps = await Document.getInitialProps(ctx);</pre><pre>      return {<br>        ...initialProps,<br>        styles: (<br>          &amp;lt;&amp;gt;<br>            {initialProps.styles}<br>            //highlight-next-line               <br>            {sheet.getStyleElement()}<br>          <br>        )<br>      };<br>    } finally {<br>      sheet.seal();<br>    }<br>  }<br>}</pre><p>Here the basic idea is every time our page load at the server side we need to insert our stylesheet into the document.</p><h3>6. Result</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fc5y2x&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fc5y2x&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fc5y2x%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/828ef62128290cbec9fbac0bdb1a070d/href">https://medium.com/media/828ef62128290cbec9fbac0bdb1a070d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfff3849e4f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Ajax call using React and Axios]]></title>
            <link>https://medium.com/@patelarpan2010/making-ajax-call-using-react-and-axios-e6a2ec4f9e53?source=rss-f85c5a3a7dab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a2ec4f9e53</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Arpan Patel]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 08:37:46 GMT</pubDate>
            <atom:updated>2021-07-27T08:37:46.730Z</atom:updated>
            <content:encoded><![CDATA[<p>So, you’re new in React and you’re searching for a way to make ajax requests, then this tutorial is for you.</p><p>In this tutorial, we will learn how to make an ajax call using react and Axios. But first, we need to set up our react project. For that purpose, we are going to use Facebook’s <a href="https://github.com/facebook/create-react-app">Create React App</a> boilerplate.</p><p>But wait, I forgot to mention one important thing here. We need to install nodejs in our machine. If nodejs already install in your machine then kudos to you. But if not then, Here are some resources to help you if you are on <a href="https://nodesource.com/blog/installing-nodejs-tutorial-windows/">Windows</a>, <a href="https://nodesource.com/blog/installing-nodejs-tutorial-mac-os-x/">MacOS</a> or <a href="https://nodesource.com/blog/installing-node-js-8-tutorial-linux-via-package-manager">Linux</a>.</p><h3>Project Setup</h3><p>Run the following command in your terminal</p><pre>npx create-react-app react-ajax</pre><p><a href="https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b"><em>npx</em></a><em> comes with npm 5.2+ and higher.</em></p><p>Now cd into your project directory</p><pre>cd react-ajax</pre><p>And finally, run the following command to start your app.</p><pre>npm start</pre><p>npm start command open your browser automatically and start your app at <a href="http://localhost:3000/">http://localhost:3000/.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*YZtjqWWR7SdiDfCq.gif" /></figure><h3>Time to Make an Ajax Request.</h3><p>Now we have our project setup and running. Look under src folder, you find the file name app.js. Open this file in your favorite editor and remove all unnecessary stuff. After you edit app.js, the file looks like this.</p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>      <br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default App;</pre><p>Now it’s time to add our HTTP client Axios. Run the following command in your terminal. It adds Axios to our project.</p><pre>npm install axios</pre><p>The next step is to add Axios into our app.js using the ES6 import module.</p><pre>import axios from axios</pre><p>We added Axios to our React app but we need API for making requests. For this, we can use random user API and react lifecycle method componentDidMount to initiate an ajax request.</p><h3>Why in componentDidMount?</h3><p>If you have question like the above here is the answer from the official document.</p><p>&gt; componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.</p><pre>componentDidMount() {<br>    axios.get(&#39;https://randomuser.me/api/?results=50&#39;)<br>      .then(response =&amp;gt; {<br>          console.log(response);<br>      })<br>      .catch(error =&amp;gt; {<br>        console.log(error);<br>      })<br>  }</pre><p>At this time if you reload your browser and look at the console you will see the following output in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*EVjKCY3btjGueMjz.png" /></figure><p>It shows that you’ve successfully make a ajax call using react and Axios. Now it’s time to show API response (user information) into the browser. So what are you waiting for, let’s see how we can achieve that. Put the following code above the componentDidMount method.</p><pre>constructor(props) {<br>    super(props);<br>    this.state = { <br>      data : []<br>    };<br>}</pre><p>The above code set state for our application. If you want to know more about React state then read <a href="https://daveceddia.com/visual-guide-to-state-in-react/">this article</a>.</p><p>Now we also need to update our componentDidMount method like below.</p><pre>componentDidMount() {<br>  axios.get(&#39;https://randomuser.me/api/?results=50&#39;)<br>    .then(response =&amp;gt; {<br>        const data = response.data.results;<br>        this.setState({data})<br>    })<br>    .catch(error =&amp;gt; {<br>       console.log(error);<br>    })<br>}</pre><p>Add the following line of code into App class render method</p><pre>render() {<br>  return (<br>     &lt;div&gt;<br>       { this.state.data.map((item, index) =&amp;gt; ) }<br>     &lt;/div&gt;<br>  );  <br>}</pre><p>Let us make UserList component below the App component</p><pre>const UserList = (props) =&amp;gt; (         <br>    &lt;p&gt;&lt;strong&gt;name : &lt;/strong&gt; {props.name.first}&lt;/p&gt;<br>)</pre><p>And finally, our app.js the file will look like this.</p><pre>import React, { Component } from &#39;react&#39;;<br>import axios from &#39;axios&#39;<br>class App extends Component {</pre><pre>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      data: []<br>    };<br>  }</pre><pre>  componentDidMount() {<br>    axios.get(&#39;https://randomuser.me/api/?results=50&#39;)<br>      .then(response =&amp;gt; {<br>          const data = response.data.results;<br>           this.setState({data})<br>      })<br>      .catch(error =&amp;gt; {<br>        console.log(error);<br>      })<br>  }</pre><pre>  render() {</pre><pre>    return (<br>      &lt;div&gt;<br>              { this.state.data.map((item, index) =&amp;gt; ) }<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>const UserList = (props) =&amp;gt; (         <br>    &lt;p&gt;&lt;strong&gt;name : &lt;/strong&gt; {props.name.first}&lt;/p&gt;<br>)</pre><pre>export default App;</pre><p>You can see running the app on <a href="https://codesandbox.io/s/jv73ynwz05?from-embed">codesandbox</a> or below :</p><p><a href="https://codesandbox.io/embed/jv73ynwz05?fontsize=14">https://codesandbox.io/embed/jv73ynwz05?fontsize=14</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a2ec4f9e53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>