<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Ateev Duggal - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Ateev Duggal - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 11:46:38 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Ateev/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Constructors in Java: A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Java is an object-oriented programming language that is centred around the concept of objects. Objects are like real-world entities that are created with the new keyword and occupy memory. But all this happens in the front-end code – so what about th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-constructors-in-java-a-beginners-guide/</link>
                <guid isPermaLink="false">686d6044aa83d1a2c46d6160</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ constructors ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ateev Duggal ]]>
                </dc:creator>
                <pubDate>Tue, 08 Jul 2025 18:15:32 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1751998519087/7808c004-c8e5-4e63-b293-10fa479a179f.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Java is an object-oriented programming language that is centred around the concept of objects. Objects are like real-world entities that are created with the new keyword and occupy memory. But all this happens in the front-end code – so what about the back-end? How are objects created and initialised with values?</p>
<p>This is where constructors come into play. Constructors are special types of methods with no return type. They are basically used to initialise the object, to set up its internal state, or to assign default values to its attributes.</p>
<p>In this tutorial, we will go deep into the topic of constructors in Java. You’ll learn how they work and why they are essential in object creation and Java programming. By the end, I hope you’ll understand why they’re one of the core concepts of OOP.</p>
<p>Let’s start…</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>You don’t need to know anything too advanced to start learning about constructors in Java. Just a basic understanding of Java syntax, classes, objects, methods, parameters, arguments, and access modifiers is enough to get started.</p>
<h2 id="heading-what-well-cover">What we’ll cover:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-constructors-in-java">What are Constructors in Java?</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-constructor-syntax">Constructor syntax:</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-constructors">Types of Constructors</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-default-constructor">Default Constructor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-no-argument-constructor">No Argument constructor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-parameterised-constructor">Parameterised Constructor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-copy-constructor">Copy Constructor</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-happens-behind-the-scenes-when-a-constructor-is-called-in-java">What Happens Behind the Scenes When a Constructor Is Called in Java?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-return-keyword-in-constructors">How to Use the return Keyword in Constructors</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-sample-code">Sample Code:</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-4">Example:</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-frequently-asked-questions">Frequently Asked Questions</a></p>
</li>
</ul>
<h2 id="heading-what-are-constructors-in-java"><strong>What are Constructors in Java?</strong></h2>
<p>As mentioned above, constructors are special types of methods that:</p>
<ol>
<li><p>do not have a return type (not even void), </p>
</li>
<li><p>have the same name as the class</p>
</li>
<li><p>are called automatically when an object is created using the new keyword. </p>
</li>
</ol>
<p>A constructor’s main purpose is to initialise a newly created object, to set up its internal state, or to assign default values to its attributes.</p>
<p>Constructors can also be understood as a special block of code which is called when an object is created – either automatically or manually by hard-coding it – with the values we want to initialise the object with.</p>
<p>If we’re okay with the object using default values (like 0 for numbers or null for objects), Java will handle that for us automatically. But if we want to give the object specific values when it's created, we need to write a constructor that takes those values as parameters and uses them to set up the object.</p>
<h3 id="heading-constructor-syntax"><strong>Constructor syntax:</strong></h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{

    <span class="hljs-comment">// Default constructor with access modifier</span>
    [access_modifier] ClassName(parameters...) {
        <span class="hljs-comment">// constructor body</span>
    }

}
</code></pre>
<h3 id="heading-examples">Examples</h3>
<p><strong>When the constructor is not defined explicitly</strong></p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{

    String brand;
    <span class="hljs-keyword">int</span> year;

    <span class="hljs-comment">// No constructor is defined, so Java provides a default one</span>
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        Car car1 = <span class="hljs-keyword">new</span> Car();  <span class="hljs-comment">// Java calls the default constructor</span>

        <span class="hljs-comment">// Default values: brand = null, year = 0</span>
        System.out.println(<span class="hljs-string">"Brand: "</span> + car1.brand);
        System.out.println(<span class="hljs-string">"Year: "</span> + car1.year);
    }
}
</code></pre>
<p>Output:</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcTW6FYYmq8kB1QL_vSBNqbaVBgo7hLXvqmA3l52HBh9Yvq4AN1aLIAKRqqiOz_tDcCFOTWBVoO1bgjWOD2yyt1nykuobAPQTWRayjqK0jDu2COmPxqI5AaapIyFzDbkrvreV-qyw?key=-LGNq3k7xufJJBHkVFXMZw" alt="output of the code in which there is no constructor" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>In the above code, we have a <strong>Car</strong> class with two variables:</p>
<ol>
<li><p>brand of type <code>String</code></p>
</li>
<li><p>year of type <code>int</code></p>
</li>
</ol>
<p>Since a class is just a blueprint, we need to create an object to actually use it. This is done in the <code>Main</code> class. When we create a Car object using <code>new</code> Car(), Java looks for a constructor. Because we didn’t define one, the compiler automatically provides a default constructor (one with no arguments).</p>
<p>This allows us to create the object and print its variables without any errors. The values printed will be the default ones — <code>null</code> <strong>for the</strong> <code>String</code><strong>, and</strong> <code>0</code> <strong>for the</strong> <code>int</code><strong>.</strong></p>
<p>We'll dive deeper into how this works behind the scenes later, step by step, so it becomes easier to understand.</p>
<p><strong>When we have defined a constructor</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{

    String brand;
    <span class="hljs-keyword">int</span> year;

    <span class="hljs-comment">// Constructor with parameters to initialize custom values</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Car</span><span class="hljs-params">(String brandName, <span class="hljs-keyword">int</span> modelYear)</span> </span>{
        brand = brandName;
        year = modelYear;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        Car car2 = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Toyota"</span>, <span class="hljs-number">2022</span>);  <span class="hljs-comment">// Custom values</span>

        System.out.println(<span class="hljs-string">"Brand: "</span> + car2.brand);
        System.out.println(<span class="hljs-string">"Year: "</span> + car2.year);
    }
}
</code></pre>
<p><strong>Output</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751864448284/2cbb8360-1c6d-42b8-811f-b7603625288d.png" alt="Output of the code which has a constructor." class="image--center mx-auto" width="201" height="156" loading="lazy"></p>
<p>This is the same code as before, with one key difference: this time, we’ve explicitly defined a constructor. Because of this, the output we see isn’t the default values (<code>null</code> for <code>String</code>, <code>0</code> for <code>int</code>), but the custom values we provided.</p>
<p>How does that happen? Simple – we pass values as arguments when creating the object:</p>
<p><code>Car car2 = new Car("Toyota", 2022);</code></p>
<p>These values are received by the constructor as parameters and are then used to initialize the object’s variables. As a result, instead of default values, we get the brand and year we specified.</p>
<h2 id="heading-types-of-constructors"><strong>Types of Constructors</strong></h2>
<p>There are mainly four types of constructors:</p>
<ol>
<li><p>Default Constructors</p>
</li>
<li><p>No-Arguments Constructor</p>
</li>
<li><p>Parameterised Constructor</p>
</li>
<li><p>Copy Constructor</p>
</li>
</ol>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfafO5dDmX5UA0ADQI5Q8DZSU2H_bVlHjmtKdDpMkmWB4Rhui1kR4w_BP_7-mPz6eb9KdGkVmYxYsZHa4HI044mz3O0CXtXJZBhpJr_wCqWgLO6U0BDUNzm_C9piUHfyXr84xEsoQ?key=-LGNq3k7xufJJBHkVFXMZw" alt="Types of constructors" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-default-constructor"><strong>Default Constructor</strong></h3>
<p>A type of no-argument constructor that is added by the compiler during the compilation process so that the values of the object can be initialised. It’s only added by the compiler if you don’t add one explicitly.</p>
<h4 id="heading-syntax"><strong>Syntax:</strong></h4>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyClass</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Constructor body</span>
    }

}
</code></pre>
<h4 id="heading-example"><strong>Example</strong></h4>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    <span class="hljs-comment">// No constructor defined here</span>
    <span class="hljs-comment">// Compiler will automatically add a default constructor</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Bike myBike = <span class="hljs-keyword">new</span> Bike();  <span class="hljs-comment">// Calls the compiler-provided default constructor</span>
        System.out.println(<span class="hljs-string">"Bike object created!"</span>);
    }

}
</code></pre>
<p>The code becomes the following after the compiler adds a default constructor during the compilation process:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    <span class="hljs-comment">// Compiler-added default constructor</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Bike</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>();  <span class="hljs-comment">// Calls Object class constructor</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Bike myBike = <span class="hljs-keyword">new</span> Bike();  <span class="hljs-comment">// Now calls this explicit default constructor</span>
        System.out.println(<span class="hljs-string">"Bike object created!"</span>);
    }

}
</code></pre>
<h4 id="heading-output"><strong>Output</strong></h4>
<p>Bike object created!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751867033814/3296a90c-3576-4a57-a863-fe0d1acfafa2.png" alt="Default Constructor" class="image--center mx-auto" width="524" height="287" loading="lazy"></p>
<h3 id="heading-no-argument-constructor"><strong>No Argument constructor</strong></h3>
<p>No-argument constructor is a type of constructor that you explicitly write in your code and that does not contain any parameters.</p>
<p>Now, you may be wondering…Isn't it the same as the default constructor? The answer is both yes and no.</p>
<p>There isn’t much difference between the default constructor and the no-argument constructor, as both do not take any parameters. But there is one key difference.</p>
<p>The default constructor, as we have already discussed, is a type of no-argument constructor that is automatically added by the compiler when it doesn’t find one in our code. In contrast, a no-argument constructor is a type of constructor that we write in our code. </p>
<p>In short, if the compiler is the one that is adding a constructor during the compilation process, it's called a default constructor. But if we are the ones adding the constructor, it’s called a no-argument constructor. </p>
<p>The main difference between a default constructor and a user-defined constructor is <strong>how they are created and what they do</strong>.</p>
<ul>
<li><p>A <strong>default constructor</strong> is automatically added by the compiler <strong>if we don’t add one ourselves</strong>. It doesn’t do much – it just calls the parent class (usually the <code>Object class</code>) and sets all variables to their default values. For example, <code>int</code> becomes <code>0</code>and objects become <code>null</code>.</p>
</li>
<li><p>A <strong>user-defined constructor</strong> is one that <strong>we write ourselves</strong>. We can add custom logic inside it, set custom values to variables, and use access modifiers like <code>public</code>, <code>private</code>, or <code>protected</code>. This means we can decide how the object should be set up when it is created.</p>
</li>
</ul>
<p>Note that even if we don’t write <code>super()</code> in our constructor, Java still adds it automatically unless we call another constructor with <code>this()</code> or call a different <code>super(...)</code> with parameters.</p>
<p>We will understand this deeply in the next section.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Aspect</strong></td><td><strong>Default Constructor</strong></td><td><strong>No-Argument Constructor</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Definition</strong></td><td>A constructor is automatically provided by the compiler when no other constructors exist.</td><td>A constructor explicitly written by the programmer that takes no arguments.</td></tr>
<tr>
<td><strong>Defined By</strong></td><td>Compiler</td><td>Programmer</td></tr>
<tr>
<td><strong>Custom Logic</strong></td><td>Not possible – does only basic, default initialization</td><td>Yes – can contain any initialization logic</td></tr>
<tr>
<td><strong>When Available</strong></td><td>Only if the class has no constructors defined at all</td><td>When explicitly written by the programmer</td></tr>
<tr>
<td><strong>Purpose</strong></td><td>To allow object creation with default initialization</td><td>To allow object creation with programmer-defined behavior</td></tr>
</tbody>
</table>
</div><h4 id="heading-syntax-1"><strong>Syntax:</strong></h4>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ClassName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Body (optional)</span>
    }

}
</code></pre>
<h4 id="heading-example-1"><strong>Example</strong></h4>
<p>Let's use the same Bike example we used to explain the default constructor.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Bike</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Bike object created!"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Bike myBike = <span class="hljs-keyword">new</span> Bike();
    }
}
</code></pre>
<h4 id="heading-output-1"><strong>Output:</strong></h4>
<p>Bike object created!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751868234945/565ec06d-7e4d-4415-b983-f517c721d0b9.png" alt="No Argument Construment" class="image--center mx-auto" width="650" height="277" loading="lazy"></p>
<p>In the above code, we have defined a constructor in our code while writing it. This means that it is an example of a no-argument constructor.</p>
<p>We know that both types of constructors are defined without any parameters, but what about the body? We haven’t said anything about it. Let’s see what happens if we write code with a no-argument constructor without a body:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    Bike() {
        <span class="hljs-comment">// No body</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Bike myBike = <span class="hljs-keyword">new</span> Bike(); <span class="hljs-comment">// Calls the user-defined no-argument constructor</span>
        System.out.println(<span class="hljs-string">"Bike object created!"</span>);
    }
}
</code></pre>
<h4 id="heading-output-2"><strong>Output:</strong></h4>
<p>Bike object created!</p>
<p>The code still gets compiled because the compiler adds the <code>super()</code> keyword during the compilation process, which initialises the object using the object class.</p>
<h3 id="heading-parameterised-constructor"><strong>Parameterised Constructor</strong></h3>
<p>A constructor that accepts parameters is called a parameterised constructor and is only used when we have to initialise an object’s attributes with custom values. </p>
<ul>
<li><p>Parameter refers to the variable listed in the constructor or method definition.</p>
</li>
<li><p>Argument is the actual value passed when calling the constructor or method.</p>
</li>
</ul>
<p>It gives us the flexibility of initiating our object with custom values given at the time of object creation.</p>
<h4 id="heading-syntax-2"><strong>Syntax</strong></h4>
<p>Below is the syntax for a parameterised constructor that takes one parameter:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{

    <span class="hljs-comment">// Data members (instance variables)</span>
    DataType variable1;

    <span class="hljs-comment">// Parameterized constructor</span>
    ClassName(DataType param1) {
        variable1 = param1;
    }

    <span class="hljs-comment">// Main method to create objects</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Creating object using parameterized constructor</span>
        ClassName obj = <span class="hljs-keyword">new</span> ClassName(value1);
    }
}
</code></pre>
<h4 id="heading-example-2"><strong>Example</strong></h4>
<p>We will again use the Bike example for this.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    String modelName;  <span class="hljs-comment">// instance variable</span>

    <span class="hljs-comment">// Parameterized constructor</span>
    Bike(String model) {
        modelName = model;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Pass parameter while creating the Bike object</span>
        Bike myBike = <span class="hljs-keyword">new</span> Bike(<span class="hljs-string">"Mountain Bike"</span>);
        System.out.println(<span class="hljs-string">"Bike object created! Model: "</span> + myBike.modelName);
    }
}
</code></pre>
<h4 id="heading-output-3">Output:</h4>
<p>Bike object created! Model: Mountain Bike</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751870395133/72bcbe0c-3a7c-4cc1-87d4-1ae9106b21d9.png" alt="Parameterized Constructor" class="image--center mx-auto" width="706" height="349" loading="lazy"></p>
<p>In this example, we’re working with a Bike class that has an instance variable of String data type called modelName, and a constructor to set the value of that variable.</p>
<p>The constructor takes a parameter called model and assigns it to modelName. So, when we create a new Bike object and pass in the string "Mountain Bike", the constructor stores that value in the modelName variable.</p>
<p>Because of this, when we print out the model name, we see "Mountain Bike" instead of null, which is the default value of the String data type, as now the value of the modelName has been updated.</p>
<h3 id="heading-copy-constructor"><strong>Copy Constructor</strong></h3>
<p>A copy constructor is used to create a new object as a copy of the existing object. Unlike C++, Java doesn’t have a default copy constructor. Instead, we have to create our own by creating a constructor that takes an object of the same class as a parameter and copies its fields.</p>
<h4 id="heading-syntax-3"><strong>Syntax</strong></h4>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{

    <span class="hljs-comment">// Fields</span>
    DataType1 field1;
    DataType2 field2;
    <span class="hljs-comment">// ... other fields</span>

    <span class="hljs-comment">// Normal constructor</span>
    ClassName(DataType1 f1, DataType2 f2) {
        field1 = f1;
        field2 = f2;
        <span class="hljs-comment">// ... initialize other fields</span>
    }

    <span class="hljs-comment">// Copy constructor </span>
    ClassName(ClassName other) {
        field1 = other.field1;
        field2 = other.field2;
        <span class="hljs-comment">// ... copy other fields</span>
    }
}
</code></pre>
<h4 id="heading-example-3"><strong>Example</strong></h4>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    String modelName;  <span class="hljs-comment">// instance variable</span>

    <span class="hljs-comment">// Parameterized constructor</span>
    Bike(String model) {
        modelName = model;
    }

    <span class="hljs-comment">// Copy constructor</span>
    Bike(Bike otherBike) {
        modelName = otherBike.modelName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create a Bike object using the parameterized constructor</span>
        Bike myBike = <span class="hljs-keyword">new</span> Bike(<span class="hljs-string">"Mountain Bike"</span>);
        System.out.println(<span class="hljs-string">"Bike object created! Model: "</span> + myBike.modelName);

        <span class="hljs-comment">// Create a copy of the existing Bike object using the copy constructor</span>
        Bike copiedBike = <span class="hljs-keyword">new</span> Bike(myBike);
        System.out.println(<span class="hljs-string">"Copied Bike object created! Model: "</span> + copiedBike.modelName);
    }
}
</code></pre>
<h4 id="heading-output-4"><strong>Output:</strong></h4>
<p>Bike object created! Model: Mountain Bike</p>
<p>Copied Bike object created! Model: Mountain Bike</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751874707838/772bdc8a-75d7-437d-a296-7f472fe5c764.png" alt="Copy Constructor" class="image--center mx-auto" width="435" height="289" loading="lazy"></p>
<p>In the above code, we have created a copy constructor to copy the values of the object (myBike) into a new object (copiedBike), which we have defined in the main class.</p>
<p>But the way the new object is called is a little different. Instead of passing arguments for the constructor, we have passed the original object.</p>
<h4 id="heading-why-copy-constructors"><strong>Why Copy Constructors?</strong></h4>
<p>A copy constructor is used to make a copy of the object, but you can also make a copy using the clone() method or the object.clone() method. So why do we use a copy constructor?</p>
<p>The copy constructor makes a deep copy, while the clone method makes a shallow copy of the object. There are various things that you should know before using cloning techniques, like <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/lang/CloneNotSupportedException.html">CloneNotSupportedException</a><strong>.</strong></p>
<p>On the other hand, copy constructors are clear and easy to understand, and work well with final fields. We can control how the copy happens (deep vs. shallow) and especially when we are dealing with mutable objects.</p>
<h2 id="heading-what-happens-behind-the-scenes-when-a-constructor-is-called-in-java"><strong>What Happens Behind the Scenes When a Constructor Is Called in Java?</strong></h2>
<p>So, just to recap: when we create an object using the <code>new</code> keyword, a constructor is automatically called. If we haven't defined any constructors in our class, Java automatically defines a constructor for us. </p>
<p>But while writing and running our code, we mostly focus on what’s visible in our editor, as in what we can see. Let’s dive a little deeper and explore what happens behind the scenes – at the compiler and JVM level – when an object is created and executed.</p>
<ul>
<li><p><strong>Step 1: Memory Allocation</strong> – When we create an object using a new keyword, Java allocates memory for that object in the heap. This memory is where the object’s fields (also called attributes) will be placed.</p>
</li>
<li><p><strong>Step 2: Reference Creation</strong> – A reference to this object is stored on the stack, which lets our program interact with the object that lives in the heap.</p>
</li>
<li><p><strong>Step 3: Constructor Creation</strong> – Java then determines which constructor to call. If no constructor is explicitly defined in our class, the compiler automatically inserts a constructor with no parameters.</p>
</li>
<li><p><strong>Step 4: Superclass Constructor Call</strong> – Before executing the constructor’s body, Java first calls the constructor of the superclass using the <code>super()</code> keyword. This ensures that the fields inherited from the parent class are properly initialised. If you don’t explicitly write <code>super()</code>, the compiler adds it automatically in the first line of the code, but only if the superclass has a no-argument constructor, unless we're already calling another constructor via <code>this()</code>.</p>
</li>
</ul>
<p>But don’t use both the <code>super()</code> and <code>this()</code> keywords in the same constructor (you can use them in separate constructors.</p>
<p>Let’s say that it doesn’t have a super class – then what? </p>
<p>The answer is simple: Java has an in-built Object class that has a no-argument constructor by default.  This is why our classes run smoothly even if we don’t write super() ourselves, as Java calls it in the background. </p>
<p>That means every class we create is a subclass of the object class:</p>
<h4 id="heading-attribute-initialisation">Attribute Initialisation:</h4>
<p>At this point, fields get initialised:</p>
<ul>
<li><p>First, with default values (for example, 0 for int, null for objects),</p>
</li>
<li><p>Then, with any explicit initialisations we've written (for example, int x = 10), the default values will get replaced by them.</p>
</li>
</ul>
<h4 id="heading-constructor-execution">Constructor Execution:</h4>
<p>And finally, the logic runs. This is where all or some of the attributes defined in the class for object creation are initialised by the parameters used during object creation, with the help of constructors. </p>
<p>But not every field may get initialised. Fields that are not updated by the constructor will keep the values they already have (either the default value or the explicitly initialised values). </p>
<p>In short, the constructor gives us the flexibility to customise our object at the time of creation, but it doesn't automatically set every field unless we explicitly write the logic for it.</p>
<p>Check the code below to understand better:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>{

    <span class="hljs-keyword">int</span> a;           <span class="hljs-comment">// default 0</span>
    <span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;      <span class="hljs-comment">// explicitly initialized to 10</span>
    String name;     <span class="hljs-comment">// default null</span>

    Example(<span class="hljs-keyword">int</span> x) {
        a = x;       <span class="hljs-comment">// only 'a' is set through constructor</span>
        <span class="hljs-comment">// 'b' is not changed, stays 10</span>
        <span class="hljs-comment">// 'name' is not changed, stays null</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"a = "</span> + a);
        System.out.println(<span class="hljs-string">"b = "</span> + b);
        System.out.println(<span class="hljs-string">"name = "</span> + name);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Example obj = <span class="hljs-keyword">new</span> Example(<span class="hljs-number">5</span>);
        obj.display();
    }
}
</code></pre>
<p><strong>Output:</strong></p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfRr6j8-QeGffPm7DYMImJL5s9X-apEGhLzXAv_cNw2CcwONejKxd4-_xKbmdKGSW1w09lt3Pib_psv7RLkd5LJ1uUxd9LSU2KOcDU9kYeqjYbZWS-qUN1PuLbNV8uF0M373kl7Cw?key=-LGNq3k7xufJJBHkVFXMZw" alt="Output of the code explaining how constructor work." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>In the above example, we have three data members – a, b, and name. We have already done the declaration and initialisation of the variable b at the beginning and given a value to a at the time of object creation.</p>
<p>So we can see that:</p>
<ol>
<li><p>‘<strong>a</strong>’, whose value has been updated by the constructor with the value given at the time of object creation, has the same value</p>
</li>
<li><p><strong>‘b’,</strong> which already had a value and does not get updated by the constructor, prints the same value </p>
</li>
<li><p>the string <strong>‘name’</strong> didn’t have a value, so null was printed instead, as it is the default value of the String data type.</p>
</li>
</ol>
<h2 id="heading-how-to-use-the-return-keyword-in-constructors"><strong>How to Use the</strong> <code>return</code> <strong>Keyword in Constructors</strong></h2>
<p>We know that constructors are defined without a return type, but we can use the return keyword in the constructor only to exit the constructor early, not to return a value. Check out the code below.</p>
<h3 id="heading-sample-code"><strong>Sample Code:</strong></h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    String modelName;  <span class="hljs-comment">// instance variable</span>
    <span class="hljs-keyword">int</span> speed;

    <span class="hljs-comment">// Parameterized constructor</span>
    Bike(String model, <span class="hljs-keyword">int</span> sp) {
        modelName = model;
        <span class="hljs-keyword">return</span>;
        speed = sp;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Pass parameter while creating the Bike object</span>
        Bike myBike = <span class="hljs-keyword">new</span> Bike(<span class="hljs-string">"Mountain Bike"</span>, <span class="hljs-number">20</span>);
        System.out.println(<span class="hljs-string">"Bike object created! Model: "</span> + myBike.modelName);
        System.out.println(<span class="hljs-string">"Speed of the Bike is "</span> + myBike.speed);
    }
}
</code></pre>
<p>Let’s try to understand the above code and the use of the return keyword along with it. We will start with what would happen if the return keyword wasn’t here. The code would have executed without any errors and would have received an output.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdRpxqN-7mjbNNenChHDcIxtufG5P4LQOG1GXo4L7_kFz955k-YF2HJfy96ZoIbPtxy3flUKiw4Mq6C8qSdZEnw3bzg5rbAy3BR4Q4x7uO2EjZfN7zFGDRlCWbAth_s97TGvoHpCQ?key=-LGNq3k7xufJJBHkVFXMZw" alt="code without the return keyword" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Now, what will happen if we add the return keyword? As we have discussed above, the return keyword will tell the compiler not to go beyond this point in the constructor. </p>
<p>So whatever we have written in the constructor after the return keyword will not be compiled, and if that had any value and was necessary for the proper execution of our code, the compiler will throw an error.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXc63VgyWkEdvcPr8x9TkVb-ZJKuPO2Z-ips_sNT70zGwFYRRdzfYYWG1Bfwnjmdypz-Pt8YS6SwQGBKMNrNhz4J27psGuOxz9Fs0gLVpM0oHzn5N1J0w3wgL7HU7rUQlB200qoRoA?key=-LGNq3k7xufJJBHkVFXMZw" alt="code with the return keyword" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The error says it clearly ‘unreachable statement’, which means that the compiler was not allowed to go beyond the return keyword. </p>
<p>Now that you understand the return keyword, let’s see when you can use it.</p>
<h3 id="heading-example-4"><strong>Example:</strong></h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{

    <span class="hljs-comment">// Constructor with a condition to exit early</span>
    Bike(<span class="hljs-keyword">boolean</span> skip) {
        <span class="hljs-keyword">if</span> (skip) {
            System.out.println(<span class="hljs-string">"Constructor exited early"</span>);
            <span class="hljs-keyword">return</span>; <span class="hljs-comment">// Ends constructor execution here</span>
        }

        System.out.println(<span class="hljs-string">"Constructor continues..."</span>);
        <span class="hljs-comment">// More initialization logic can go here</span>
        System.out.println(<span class="hljs-string">"Bike object initialized successfully"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        System.out.println(<span class="hljs-string">"Creating first bike (skip = true):"</span>);
        Bike bike1 = <span class="hljs-keyword">new</span> Bike(<span class="hljs-keyword">true</span>);  <span class="hljs-comment">// Constructor will exit early</span>

        System.out.println(<span class="hljs-string">"\nCreating second bike (skip = false):"</span>);
        Bike bike2 = <span class="hljs-keyword">new</span> Bike(<span class="hljs-keyword">false</span>); <span class="hljs-comment">// Constructor will continue</span>
    }
}
</code></pre>
<p>We’ve defined a Bike class that has a constructor with one boolean parameter called skip. Inside the constructor, there's an if statement that checks if skip is true. If it is, the constructor prints a message and uses the return keyword to exit early. This means the rest of the constructor won’t run.</p>
<p>But there is no else block. So what happens when skip is false? In that case, the if condition is not true, then the code inside the if statement is not executed (including the return keyword) and the constructor simply continues to the next lines of code. That’s where we do the actual bike initialisation and print a success message.</p>
<p>In short:</p>
<ol>
<li><p>If skip is true, the constructor exits early.</p>
</li>
<li><p>If skip is false, the constructor continues and finishes the setup.</p>
</li>
</ol>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeK-1kbbG97wMT_d-zrZ28eCuVsWZEkH6Ve3kuYSyXM1e-pZDsJl8K1S4GVfp54XnxGLOGGH_y_B3lZvmy1GRSvOY5Xp_rqHZd7jdNHHxdVAdVuW5vM__6DU99SdS38b03jXjkj?key=-LGNq3k7xufJJBHkVFXMZw" alt="output of the example explaining return keyword" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>This is a simple way to control how much of the constructor runs, based on a condition.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this blog, we have understood many different topics, what a constructor is, its different types, like default constructor, no argument constructor, parameterised constructor and copy constructor, not only with theory but with code examples as well.</p>
<p>Understanding them will not only enhance our understanding but also help us write modular and well-maintained code in Java. While this concept is also important in OOP, as it is centred around the concept of objects and constructors are the ones that are used to initialise them.</p>
<h2 id="heading-frequently-asked-questions"><strong>Frequently Asked Questions</strong></h2>
<p><strong>Q1. Why do we use constructors?</strong></p>
<p><strong>A:</strong> We use constructors because:</p>
<ol>
<li><p>They are created automatically by the compiler and initialise the object with default values.</p>
</li>
<li><p>We can initialise all the attributes of the objects in one go.</p>
</li>
<li><p>They prevent incomplete or incorrect object initialisation by ensuring that important data is provided during object creation.</p>
</li>
<li><p>Code maintainability and modularity increase.</p>
</li>
<li><p>We can use objects as soon as they are created.</p>
</li>
</ol>
<p><strong>Q2. What is the basic difference between Method Overloading and Constructor Overloading?</strong></p>
<p><strong>A:</strong> </p>
<table><tbody><tr><td><p><strong>Feature</strong></p></td><td><p><strong>Method Overloading</strong></p></td><td><p><strong>Constructor Overloading</strong></p></td></tr><tr><td><p><strong>Purpose</strong></p></td><td><p>To perform different operations with the same method name</p></td><td><p>To create objects with different initialisations</p></td></tr><tr><td><p><strong>Return Type</strong></p></td><td><p>Can have a return type</p></td><td><p>Has no return type</p></td></tr><tr><td><p><strong>Name</strong></p></td><td><p>Can be any valid method name</p></td><td><p>Always has the same name as the class</p></td></tr><tr><td><p><strong>Usage Context</strong></p></td><td><p>Called on existing objects</p></td><td><p>Called when creating objects</p></td></tr></tbody></table>

<p>You can check out some of my other beginner-friendly articles on my blog:</p>
<ol>
<li><p><a target="_blank" href="https://tekolio.com/what-is-abstraction-in-java-and-how-to-achieve-it/">Understanding abstraction in Java</a></p>
</li>
<li><p><a target="_blank" href="https://tekolio.com/how-to-build-a-movie-app-in-react-using-tmdb-api/">How to build a Movie App in React using TMDB API?</a></p>
</li>
<li><p><a target="_blank" href="https://tekolio.com/how-to-merge-two-sorted-arrays/">How to merge two sorted arrays</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Make an Image Search App in React using the Unsplash API ]]>
                </title>
                <description>
                    <![CDATA[ Unsplash is a site where you can download free and unlicensed images and use them as you see fit. In this tutorial, we will make an Image Search App using the Unsplash API to get access to its enormous collection of images and also download them. Bef... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-an-image-search-app-in-react/</link>
                <guid isPermaLink="false">66d45d9ac7632f8bfbf1e3d3</guid>
                
                    <category>
                        <![CDATA[ image ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ateev Duggal ]]>
                </dc:creator>
                <pubDate>Mon, 04 Apr 2022 22:19:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/Unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Unsplash is a site where you can download free and unlicensed images and use them as you see fit.</p>
<p>In this tutorial, we will make an Image Search App using the Unsplash API to get access to its enormous collection of images and also download them.</p>
<p>Before starting the development part of our app, let’s see how it will <a target="_blank" href="https://unspalsh-app-in-react.vercel.app/">look exactly</a>.</p>
<p>Let’s start…</p>
<h2 id="heading-contents">Contents</h2>
<ol>
<li><p>How to Create the React App</p>
</li>
<li><p>How to Build the UI of our App</p>
</li>
<li><p>How to Get the Access Key and API Endpoint from Unsplash</p>
</li>
<li><p>How to Use Hooks in our App</p>
</li>
<li><p>How to Display Images in our App</p>
</li>
<li><p>How to Handle Errors</p>
</li>
<li><p>Conclusion</p>
</li>
</ol>
<h3 id="heading-what-will-we-learn">What will we learn?</h3>
<p>This project is mainly for beginners, but anyone who wants to brush up their skills can follow along. In this tutorial, you will learn:</p>
<ol>
<li><p>How to get API endpoints and Access Keys from the Unsplash developer's dashboard.</p>
</li>
<li><p>How to use the useState and useEffect hooks to fetch data from the API.</p>
</li>
<li><p>How to use the map function to display images or any other data from the API.</p>
</li>
</ol>
<h2 id="heading-how-to-create-the-react-app">How to Create the React App</h2>
<p>It's very easy to create a React app – just go to your working directory in your preferred IDE and enter the following command in the terminal:</p>
<pre><code class="lang-javascript">npx create-react-app image-search-app
</code></pre>
<p>If you are unsure how to properly set up a create-react-app project, you can refer to the official guide here at <a target="_blank" href="https://create-react-app.dev/docs/getting-started/">create-react-app-dev</a>.‌‌</p>
<p>After the setup, run npm start in the same terminal to start localhost:3000 where our React app will be hosted. We can also see all our changes there.</p>
<h2 id="heading-how-to-build-the-ui-of-our-app">How to Build the UI of our App</h2>
<p>There will be two sections in the UI of our App:</p>
<ol>
<li><p>The Input section</p>
</li>
<li><p>The Result section where we will show the images</p>
</li>
</ol>
<p>In the input section, we have an input tag in which we will write the search term or query. We also have a button with an <strong>onClick</strong> event handler which will trigger the function responsible for fetching the data from the API.</p>
<pre><code class="lang-html">import React from "react";
const App = () =&gt; {
  return (
    <span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container-fluid"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"row"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"col-12 d-flex justify-content-center align-items-center input"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
              <span class="hljs-attr">className</span>=<span class="hljs-string">"col-3 form-control-sm py-1 fs-4 text-capitalize border border-3 border-dark"</span>
              <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
              <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Search Anything..."</span>
            /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
              <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>
              <span class="hljs-attr">onClick</span>=<span class="hljs-string">{Submit}</span>
              <span class="hljs-attr">className</span>=<span class="hljs-string">"btn bg-dark text-white fs-3 mx-3"</span>
            &gt;</span>
              Search
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span>
  );
};
export default App;
</code></pre>
<p>The output will be the following:</p>
<p><img src="https://lh4.googleusercontent.com/qzIWk69MB4RvIfXj7neJ3mhg1q3G1S96r42xsyVFIEcU7IUXBUiT4H7dMP7mSDDHiVOtM1LAycPF2DO5pN6_wanvWbgyED1K3YmeXvE7uNuiYYImV8e7CNXGY4kB0_9B8du3Qxi2" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this article, we will not be discussing the styling part of the app. This way we can stay more focused on the React part which is more necessary to understand.</p>
<h2 id="heading-how-to-get-the-access-key-and-api-endpoint-from-unsplash">How to Get the Access Key and API Endpoint from Unsplash</h2>
<p>Let's get those API keys from <a target="_blank" href="https://unsplash.com/developers">Unsplash for Developer</a>. follow the steps given below to get your API key and other details:</p>
<p>First, go to the above link and click register as a developer.</p>
<p><img src="https://lh6.googleusercontent.com/xB8Tb3HKYAGv5b7ArmtT6zuU3aGTF_uO6-9kiTiFEBlEmsNkUJagAmzq1zI64RAasNivbO2uFpYe6lC9qcK6-BCjwy2V-p-qX-UqdvjCJO-y6Kjm_bpmRNwr_q277Vc-GKwcIqG_" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then fill in the credentials they have asked for:</p>
<p><img src="https://lh3.googleusercontent.com/uMKaffa_5TJDMRHXl8WUCsUc3MxcyAAlwVbkCVpkbQ8c21qfV_8U9c2toKfJ-WcLj387vgJhTN54xq8MoCJO82cO68eAePTmUd7RqinyYG4659h8LazgueEWlrhEZEV0EbcO-psH" alt="Image" width="600" height="400" loading="lazy"></p>
<p>After this, you will be directed to the developer dashboard. Click on the new project.</p>
<p><img src="https://lh6.googleusercontent.com/_FQN1PymEdAKDYwB0YR7MeUL6Ab6nPyLUkCb40SBg6jZNZj7vnxLnSRVu24NALBfbanpdF4qxze9p9xba8CRZWfTtCjp6PmNv7o12fUip3pLYAvHKqq16-d3bO7_897Df_mUQ_l4" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You will be asked to accept all the terms written there. Read them if you want or else just check all of them and click the button at the end to proceed.</p>
<p><img src="https://lh5.googleusercontent.com/IcLYr5HycXD28nEgtLF4_6Tj6Waa9XAU5B1GHf1Z-5Mrmils4seAa4gvY4kearxFkJhe0hv7p3IFau9iQdbF8a8YGVVZ-TF56y8P5T68YPWZ8H1A-ipAiVs6tONFl2kYYojQNSWa" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next, a modal form will appear as shown below in which you have to write the application information like name and description.</p>
<p>Then click Create Application.</p>
<p><img src="https://lh3.googleusercontent.com/1Av2BfGSaXi0S9Bib2qkcaxcgioFUGMRqveNWKyMATeJG-cHkpCKAfNh4KQP4ztvhMQ7R1jcBe4x4gRnMoSbpr0oxmczqxCscgFmALMpQDSo6Zm3CLbyZbUVx7n4BF2DO75l_qVv" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now that our application has been created, we can access the <strong>Access Key</strong> and <strong>Secret Key</strong> under the <strong>Keys section</strong>:</p>
<p><img src="https://lh5.googleusercontent.com/PWKObP8aBkr8dipYCoq5lkkRC1TYbgrZcoNbo0DeunoNsoXMMqYayleGDwCjig9iXZ4eSrq4bNgsLoQ9e5Q7ohMKw9VDoajmSmvo8sI7aZKnDV3amuVRd_7agognh90R8Fkou_cs" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice that at the very beginning of this page, it says <strong>Demo</strong>. This means that our application has been accepted but is still in development mode.</p>
<p>In this mode, we can only make 50 requests per hour. If we exceed this limit, our API will not work and the images will not load.</p>
<p><img src="https://lh3.googleusercontent.com/iPG7K3Wl9-HOuQbAmrnhyDq5u-tplTZJ56YbDKHMpgIJ4wANdSQPBBjN_fWMPR-89RvEvEG9yYiOWGyUCnU-Qh88EXC7z1rfJ_IvnfsHhXJ5YFVMT6GkaG8WsvT4ZHlJbU86D951" alt="Image" width="600" height="400" loading="lazy"></p>
<p>After this, head over to the documentation and select the option “<strong>Search Photos by Keyword</strong>”.</p>
<p><img src="https://lh6.googleusercontent.com/4cMwgogWv858cVvy78oWmNce-GC0rZBSpFaadMh_eO-qbJ3pVHMPL90b_dUQNonSj9-NeRxvhM9hj5JZGuViTjFESmIo5m6yRWUS-gtrEuh5TA5ugLT9PCxvgbZ-3oPdbKZ9pl_z" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Scroll down to the <strong>Response</strong> Section and copy the link as shown:</p>
<p><img src="https://lh4.googleusercontent.com/3ORXGCncj8J8CxUwTYP4tesP9F-IjFSCADrAQQ0KN4DcrlmjepMvmaudZc5PZTUfzPkFdjI9IdRnDa2JYHabqJgsPHKccboA9wiDMg3SaoV9nA554OjIzRKYOHQ_g2I_p2-uJk75" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>API endpoint</em></p>
<p>Now we have both our <strong>API key and the API endpoint</strong>. Let's proceed with our App.</p>
<h2 id="heading-how-to-use-hooks-in-our-app">How to Use Hooks in our App</h2>
<p>We will be using the useState and useEffect hooks in our app. They'll let us set the states which are required to get the value of input and search the API for data regarding that value.</p>
<p>For hooks to work, we have to define them at the very top of our app like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
</code></pre>
<h3 id="heading-how-to-set-state-using-the-usestate-hook">How to Set State Using the useState Hook</h3>
<p>As we discussed above, we'll use hooks to extract data from the API using the value searched in the input field. That value will be read by our React app using the useState hook.</p>
<p>We define states using this hook for specific purposes. In this app, we will be defining two of them: one for getting the value from the input field and the other to display results fetched from the API.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [img, setImg] = useState(<span class="hljs-string">""</span>);
<span class="hljs-keyword">const</span> [res, setRes] = useState([]);
</code></pre>
<p>There are two parameters in the above code used to define the useState hook: one of them is the state which we will use to store values, and the other is the function that we will be using to update the state values. Read more about <a target="_blank" href="https://tekolio.com/what-is-the-usestate-hook-in-react/">useState hook here</a>.</p>
<p>We have defined the first state as an empty string as it will be used to store the input from the search bar (and that is also a string).</p>
<p>The other state is initialized as an empty array because it will store the data fetched from the API and then show it in our Result Section</p>
<p>By default, we can only get up to 10 data points per API, but we can exceed that using a parameter <strong>per_page</strong> which we will see later in this tutorial.</p>
<h3 id="heading-how-to-use-the-img-state">How to use the img state</h3>
<p>The next step is to store the value of the input text field into the <strong>img</strong> state using the value attribute of the input tag. Then we add an onChange() event handler to it. This onChange() event handler will have a function that will be used to update the state using the <strong>e.target.value.</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span>
  <span class="hljs-attr">className</span>=<span class="hljs-string">"col-3 form-control-sm py-1 fs-4 text-capitalize border border-3 border-dark"</span>
  <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
  <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Search Anything..."</span>
  <span class="hljs-attr">value</span>=<span class="hljs-string">{img}</span>
  <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setImg(e.target.value)}
/&gt;;
</code></pre>
<h3 id="heading-how-to-make-api-requests-to-unsplash-using-the-useeffect-hook">How to Make API Requests to Unsplash using the useEffect Hook</h3>
<p>We will now use the Unsplash API and the Access key we have acquired in the above step to fetch data and display it in our app.</p>
<p>For this, we will again need a state to store the data fetched from the API which we have already defined in the above section (<strong>res</strong>, which is initialized as an empty array for this purpose only).</p>
<p>There are many methods in JavaScript we can use to fetch data from an API, but we will be using the async-await method – it's by far the simplest one.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchRequest = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetch(
    <span class="hljs-string">`https://api.unsplash.com/search/photos?page=1&amp;query=<span class="hljs-subst">${img}</span>&amp;client_id=<span class="hljs-subst">${Access_Key}</span>`</span>
  );
  <span class="hljs-keyword">const</span> dataJ = <span class="hljs-keyword">await</span> data.json();
  <span class="hljs-keyword">const</span> result = dataJ.results;
  <span class="hljs-built_in">console</span>.log(result);
  setRes(result);
};
useEffect(<span class="hljs-function">() =&gt;</span> {
  fetchRequest();
}, []);
</code></pre>
<p>Notice that we have written <code>${Access_Key}</code> – here we have to write our access key. We complete this step to secure our API key as anyone can misuse it.</p>
<p>In Unsplash, we can also apply for the production of our app, and by doing so we can go online with the images that Unsplash has to offer.</p>
<p>For this reason, everyone gets a different set of Access Keys and Security Keys. It's always best to hide these keys from others so that it doesn’t get misused and we pay the price for that.</p>
<p>In the above code, we have initially stored the data fetched from the API into the <strong>data</strong> variable which is then converted into JSON for simplicity's sake. This lets us read the data and extract the necessary values, which are stored in the <strong>dataJ</strong> variable and consoled to check if we are getting the value we need or not.</p>
<p><img src="https://lh4.googleusercontent.com/U32k-__bIyqEnF_2xPC1zT293GOGH7bY-_TVWbdzhfcSkMMMbuNC1bgExFM-HETrJJvVcFC1VzunOWtJ4hq1Gh72mmuPwv6A71V-QD0luGl42wJ6gmUlQTrtj-l4tp2Ay1FjuUP1" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>API in JSON format</em></p>
<p>And if we open any one of the above search results to see what values are there for us to extract:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"total"</span>: <span class="hljs-number">133</span>,
    <span class="hljs-attr">"total_pages"</span>: <span class="hljs-number">7</span>,
    <span class="hljs-attr">"results"</span>: [
    {
    <span class="hljs-attr">"id"</span>: <span class="hljs-string">"eOLpJytrbsQ"</span>,
    <span class="hljs-attr">"created_at"</span>: <span class="hljs-string">"2014-11-18T14:35:36-05:00"</span>,
    width: <span class="hljs-number">4000</span>,
    height: <span class="hljs-number">3000</span>,
    color: <span class="hljs-string">"#A7A2A1"</span>,
    blur_hash: <span class="hljs-string">"LaLXMa9Fx[D%~q%MtQM|kDRjtRIU"</span>,
    likes: <span class="hljs-number">286</span>,
    liked_by_user: <span class="hljs-literal">false</span>,
    description: <span class="hljs-string">"A man drinking a coffee."</span>,
    user: {
    id: <span class="hljs-string">"Ul0QVz12Goo"</span>,
    username: <span class="hljs-string">"ugmonk"</span>,
    name: <span class="hljs-string">"Jeff Sheldon"</span>,
    first_name: <span class="hljs-string">"Jeff"</span>,
    last_name: <span class="hljs-string">"Sheldon"</span>,
    instagram_username: <span class="hljs-string">"instantgrammer"</span>,
    twitter_username: <span class="hljs-string">"ugmonk"</span>,
    portfolio_url: <span class="hljs-string">"http://ugmonk.com/"</span>,
    profile_image: {
    small:
    <span class="hljs-string">"https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&amp;q=80&amp;fm=jpg&amp;crop=faces&amp;cs=tinysrgb&amp;fit=crop&amp;h=32&amp;w=32&amp;s=7cfe3b93750cb0c93e2f7caec08b5a41"</span>,
    medium:
    <span class="hljs-string">"https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&amp;q=80&amp;fm=jpg&amp;crop=faces&amp;cs=tinysrgb&amp;fit=crop&amp;h=64&amp;w=64&amp;s=5a9dc749c43ce5bd60870b129a40902f"</span>,
    large:
    <span class="hljs-string">"https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&amp;q=80&amp;fm=jpg&amp;crop=faces&amp;cs=tinysrgb&amp;fit=crop&amp;h=128&amp;w=128&amp;s=32085a077889586df88bfbe406692202"</span>,
    },
    links: {
    self: <span class="hljs-string">"https://api.unsplash.com/users/ugmonk"</span>,
    html: <span class="hljs-string">"http://unsplash.com/@ugmonk"</span>,
    photos: <span class="hljs-string">"https://api.unsplash.com/users/ugmonk/photos"</span>,
    likes: <span class="hljs-string">"https://api.unsplash.com/users/ugmonk/likes"</span>,
    },
    },
    current_user_collections: [],
    urls: {
    raw: <span class="hljs-string">"https://images.unsplash.com/photo-1416339306562-f3d12fefd36f"</span>,
    full: <span class="hljs-string">"https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f"</span>,
    regular:
    <span class="hljs-string">"https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=1080&amp;fit=max&amp;s=92f3e02f63678acc8416d044e189f515"</span>,
    small:
    <span class="hljs-string">"https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=400&amp;fit=max&amp;s=263af33585f9d32af39d165b000845eb"</span>,
    thumb:
    <span class="hljs-string">"https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=200&amp;fit=max&amp;s=8aae34cf35df31a592f0bef16e6342ef"</span>,
    },
    links: {
    self: <span class="hljs-string">"https://api.unsplash.com/photos/eOLpJytrbsQ"</span>,
    html: <span class="hljs-string">"http://unsplash.com/photos/eOLpJytrbsQ"</span>,
    download: <span class="hljs-string">"http://unsplash.com/photos/eOLpJytrbsQ/download"</span>,
    },
    },
    <span class="hljs-comment">// more photos ...</span>
    ],
    },
</code></pre>
<p>It's better to use this function inside the useEffect hook as it will prevent any re-rendering of the data if we made any changes in the UI of our App. To understand useEffect in-depth, <a target="_blank" href="https://tekolio.com/explaining-useeffect-hook-in-react/">click here</a>.</p>
<p>We use the <strong>setRes</strong> function to update the value of <strong>res</strong> from an empty array to an array which will store all the fetched data in the JSON format as shown above.</p>
<p>We have already given an onClick function to the button at the beginning of our app in the input section. Now it's time to define a function for this event handler which will be triggered as soon as the Search button is clicked. This function will call the <strong>fetchRequest</strong> function which will fetch the data and show us the result in the Result section.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Submit = <span class="hljs-function">() =&gt;</span> {
  fetchRequest();
  setImg(<span class="hljs-string">""</span>);
};
</code></pre>
<h2 id="heading-how-to-display-images-in-our-app">How to Display Images in our App</h2>
<p>In the above section, we have stored the data fetched from the API into the <strong>res</strong> state which has stored them in the form of an array. To get these values from there, we have to use the map method.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"col-12 d-flex justify-content-evenly flex-wrap"</span>&gt;</span>
  {res.map((val) =&gt; {
    return (
      <span class="hljs-tag">&lt;&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"col-3 img-fluid img-thumbnail"</span>
          <span class="hljs-attr">src</span>=<span class="hljs-string">{val.urls.small}</span>
          <span class="hljs-attr">alt</span>=<span class="hljs-string">"val.alt_description"</span>
        /&gt;</span>
      <span class="hljs-tag">&lt;/&gt;</span>
    );
  })}
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>;
</code></pre>
<p>If we go back and see the response in JSON, we will find a different kind of information: <strong>URLs</strong> which contains the path to the image. So here <strong>val.urls.small</strong> is the actual path to the image, and <strong>val.alt_description</strong> is the alt description of the picture.</p>
<p>There are different fields inside "urls" that give different data, such as:</p>
<ul>
<li><p><strong>Raw</strong>: Actual raw image that was taken by a user.</p>
</li>
<li><p><strong>Full</strong>: Raw image in .jpg format.</p>
</li>
<li><p><strong>Regular</strong>: Best for practical uses, width=1080px.</p>
</li>
<li><p><strong>Small</strong>: Perfect for slow internet speed, width=400px.</p>
</li>
<li><p><strong>Thumb</strong>: Thumbnail version of the image, width=200px.</p>
</li>
</ul>
<p>In this article, we will be using small, but there are others too as shown above that we can play with and find the appropriate one for us.</p>
<p><img src="https://lh4.googleusercontent.com/W8UFqJV3_yVh1-Ntvljzv09XXDjxgMwl9L_6ZiX9M5ZRAKAIbShkvJEF4XaN-UD_yI1c7o7K9s1rC5kTmuDGAaEfWDPTV4vYeIj8DUIWn57x7Y6buR8WLgRwP-oJNTHn9MHo-1iY" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Final Product</em></p>
<p>By default, the number of items that can be fetched at a time is 10, but this number can be increased or decreased depending upon how many images we want our app to show.</p>
<p>To do this we just have to add a parameter at the end of our API call (<strong>per_page</strong>) as shown in the code, and put it equal to the number of images we want to show.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchRequest = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetch(
    <span class="hljs-string">`https://api.unsplash.com/search/photos?page=1&amp;query=<span class="hljs-subst">${img}</span>&amp;client_id=<span class="hljs-subst">${Access_Key}</span>&amp;per_page=20`</span>
  );
  <span class="hljs-keyword">const</span> dataJ = <span class="hljs-keyword">await</span> data.json();
  <span class="hljs-keyword">const</span> result = dataJ.results;
  <span class="hljs-built_in">console</span>.log(result);
  setRes(result);
};
</code></pre>
<p>There are many more parameters that Unsplash has to offer. Below is a list of a few of them:</p>
<p><img src="https://lh5.googleusercontent.com/zFYDDwnZ52Cx7NUoKL31GiT_87ZeQQ0B9LZeMGShHsXUmu94FbvZHxYJnEOymSoxq-gy2RMItMppHP8cgTmJSB34djJf02Ae0Ji2nXtPbpB91muUg6D3gYrwq69fvrcAu8YVWbqv" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>parameters of Unsplash API</em></p>
<h2 id="heading-how-to-handle-errors">How to Handle Errors</h2>
<p>If we do a quick search now on, say, flags, we will get our images. But there are still some issues that need to be fixed. One of them is the error we are receiving in the console.</p>
<p><img src="https://lh4.googleusercontent.com/nNglt_EjKldYnndufDLUOsK1yxvJmywsrjK3XOmm11jhEs3EfuIudjqahEvzJRt9JBtypzpWZDsE3QBgATN9ry7vD5vPrK42zeux23YBcVQ4NzvWcYNsL1Ha6X6YP1QoK7zZRCSm" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Error in Console</em></p>
<p>To fix this, pass a unique key to every child using the id of the image. This key prop explicitly tells React the identity of each child in a list. This also prevents children from losing state between renders.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"col-12 d-flex justify-content-evenly flex-wrap"</span>&gt;</span>
  {res.map((val) =&gt; {
    return (
      <span class="hljs-tag">&lt;&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span>
          <span class="hljs-attr">key</span>=<span class="hljs-string">{val.id}</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"col-3 img-fluid img-thumbnail"</span>
          <span class="hljs-attr">src</span>=<span class="hljs-string">{val.urls.small}</span>
          <span class="hljs-attr">alt</span>=<span class="hljs-string">"val.alt_description"</span>
        /&gt;</span>
      <span class="hljs-tag">&lt;/&gt;</span>
    );
  })}
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>;
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we have developed a Photo Search app in React using the Unsplash API. While building our app, we discussed many things like how to use React Hooks to get the data from an API and use it to display images in our App.</p>
<p>There is much more you can do with this application to extend it. For example, we could add a Random button to display random images, create a checkbox to toggle between searching for photos or the users that posted them according to the user’s preference, add an <a target="_blank" href="https://www.npmjs.com/package/react-infinite-scroll-component">infinite scroll</a> to display more images, and more.</p>
<p>You can go through some of my other beginner-friendly, project-based articles here:</p>
<ol>
<li><p><a target="_blank" href="https://tekolio.com/how-to-make-a-table-in-react-with-hooks/">How to Make a Table in React using Hooks with Multiple Features</a></p>
</li>
<li><p><a target="_blank" href="https://tekolio.com/how-i-made-my-portfolio-in-react/">How I made my Portfolio in React</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-make-a-filter-component-in-react/">How to Make a Filter Component in React</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use PropTypes in React ]]>
                </title>
                <description>
                    <![CDATA[ PropTypes are a good first line defense when it comes to debugging your apps. But before getting into detail about PropTypes, we have to understand the concept of props. Props are the read-only properties that are shared between components to give th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-proptypes-in-react/</link>
                <guid isPermaLink="false">66d45d9ccc7f04d2549a372a</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ateev Duggal ]]>
                </dc:creator>
                <pubDate>Mon, 14 Feb 2022 16:36:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/props.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>PropTypes are a good first line defense when it comes to debugging your apps. But before getting into detail about PropTypes, we have to understand the concept of props.</p>
<p><a target="_blank" href="https://tekolio.com/what-are-props-in-react-and-how-to-use-them/">Props</a> are the read-only properties that are shared between components to give the unidirectional flow of React a dynamic touch. They're mainly shared from the parent component to the child component, but the reverse is also possible (though not recommended).</p>
<p>In this blog, we will discuss how to validate or check the props that we are passing to avoid complex debugging at a later stage.</p>
<h2 id="heading-what-are-proptypes">What are PropTypes?</h2>
<p>PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don’t receive an error at the very end of our app by the console which might not be easy to deal with.</p>
<p>I don't recommend using them in short apps like projects for self-practice but it's totally up to you. For larger projects like for a client, it's often a wise choice and a good practice to use them.</p>
<p>There are many different types of PropTypes and all of them have their unique ES6 classes which we can use. We will discuss every type in this article.</p>
<h2 id="heading-how-to-use-proptypes">How to use PropTypes</h2>
<p>Before the release of React 15.5.0, PropTypes were available in the React package, but now we have to add the prop-types library in our project.</p>
<p>We can do so by running the following command in our terminal:</p>
<pre><code class="lang-javascript">npm install prop-types --save
</code></pre>
<p>We can use PropTypes to validate any data we are receiving from props. But before using it we will have to import it as always in our app:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">'prop-types'</span>;
</code></pre>
<p>They are often used after the component ends and starts with the name of the component as shown:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { PropTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;

<span class="hljs-keyword">const</span> Count = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      .........
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
};

Count.propTypes = {
  <span class="hljs-comment">//// key is the name of the prop and</span>
<span class="hljs-comment">// value is the PropType</span>
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Count;
</code></pre>
<p>PropTypes are also objects with a key and a value pair where the ‘key’ is the name of the prop while the value represents the type or class by which they are defined.</p>
<p>Since defining PropTypes on a component does not depend on the component implementation, we will be leaving out the code for the component itself in all the following examples. The code above can be simplified to the following:</p>
<pre><code class="lang-javascript">Count.propTypes = {
<span class="hljs-comment">// Put props here</span>
}
</code></pre>
<p>Let's discuss how many types of PropTypes are there before understanding them with an example.</p>
<h2 id="heading-basic-types-of-proptypes">Basic Types of PropTypes</h2>
<p>The most basic way we can check a prop's type is by checking if it falls under the category of primitive types in JavaScript, such as a boolean, string, object, and so on.</p>
<p>Below is the list of all data types that are considered primitive or the basic ones with their classes that we can use to check props.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Type</strong></td><td><strong>Class</strong></td><td><strong>Example</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>String</strong></td><td>PropType.string</td><td>“helllo”</td></tr>
<tr>
<td><strong>Object</strong></td><td>PropType.object</td><td>{name: “Rohit”}</td></tr>
<tr>
<td><strong>Number</strong></td><td>PropType.number</td><td>10</td></tr>
<tr>
<td><strong>Boolean</strong></td><td>PropType.bool</td><td>true/false</td></tr>
<tr>
<td><strong>Function</strong></td><td>PropType.func</td><td>const say = {console.log(“hello”)}</td></tr>
<tr>
<td><strong>Symbol</strong></td><td>PropType.symbol</td><td>Symbol(“m”)</td></tr>
</tbody>
</table>
</div><p>Below is an example that shows us how to use these PropTypes for type checking in our app. As we discussed already, they are defined as objects with a key and a value pair where the key is the name of the object while value contains the classes which will be used for type checking.</p>
<pre><code class="lang-javascript">Count.propTypes = {
  <span class="hljs-attr">name</span>: PropTypes.string,
  <span class="hljs-attr">age</span>: PropTypes.number,
  <span class="hljs-attr">address</span>: PropTypes.object,
  <span class="hljs-attr">friends</span>: PropTypes.array,
};
</code></pre>
<p>In the above code, the name prop is expected to have a value which is a string, age is a number, address is an object, and friends is an array. If any value other than this has been used for the same props as a value, it will show an error in the console like this:</p>
<p><img src="https://lh3.googleusercontent.com/NoiuFl2D3WofbIe7_CsqbNkolVLFzXyPSvvADV3LvFug2jp2oMhBXFl42Qy79e4LkGAOio5RD5rAhlUOBJEoSP3oDUuWNwxb1wCfQYdYQpWvdtDbKQQDkwt0rMSD9dlQAhXozKKC" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Console error for wrong PropTypes</em></p>
<p>We can chain any of the above with <code>isRequired</code> to make sure a warning is shown if the prop isn't provided.</p>
<pre><code class="lang-javascript">Count.propTypes = {
  <span class="hljs-attr">basicObject</span>: PropTypes.object,
  <span class="hljs-attr">numbers</span>: PropTypes.objectOf(PropTypes.numbers),
  <span class="hljs-attr">messages</span>: PropTypes.instanceOf(Message),
  <span class="hljs-attr">contactList</span>: PropTypes.shape({
    <span class="hljs-attr">name</span>: PropTypes.string.isRequired,
    <span class="hljs-attr">phone</span>: PropTypes.string.isRequired,
  }),
};
</code></pre>
<h2 id="heading-collective-type">Collective Type</h2>
<p>We have seen how to validate or check to see what category of basic data type props fall into. But there are many more ways that props can be passed and used – such as collective types like an array of numbers, strings, and so on. So what about them?</p>
<p>We can also check the props for them. Below are the various ways in which a data type can be combined and used.</p>
<h3 id="heading-array-types">Array Types</h3>
<p>Here we will discuss all the possibilities that can be formed with an array with their examples just like we saw with basic types.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Type</strong></td><td><strong>Class</strong></td><td><strong>Example</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Array</strong></td><td>PropTypes.array</td><td>[]</td></tr>
<tr>
<td><strong>Array of numbers</strong></td><td>PropTypes.arrayOf([type])</td><td>[1,2,3]</td></tr>
<tr>
<td><strong>Array of string</strong></td><td>PropTypes.oneOf([arr])</td><td>[“Red”, “blue”]</td></tr>
<tr>
<td><strong>Array of objects</strong></td><td>PropTypes.oneOfType([types])</td><td>PropTypes.string,</td></tr>
</tbody>
</table>
</div><pre><code class="lang-javascript">Count.propTypes = {
  <span class="hljs-attr">counts</span>: PropTypes.array,
  <span class="hljs-attr">users</span>: PropTypes.arrayOf(PropTypes.object),
  <span class="hljs-attr">alarmColor</span>: PropTypes.oneOf([<span class="hljs-string">'red'</span>, <span class="hljs-string">'blue'</span>]),
  <span class="hljs-attr">description</span>: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.instanceOf(Title)
  ]),
  }
</code></pre>
<h3 id="heading-object-types">Object Types</h3>
<p>Just like the array types, here are some of the collective object types:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Type</strong></td><td><strong>Class</strong></td><td><strong>Example</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Object</strong></td><td>PropTypes.object</td><td>{name: “Anu”}</td></tr>
<tr>
<td><strong>Number Object</strong></td><td>PropTypes.objectOf()</td><td>{age: 25}</td></tr>
<tr>
<td><strong>Object Shape</strong></td><td>PropTypes.shape()</td><td>{name: PropTypes.string,</td></tr>
<tr>
<td><strong>Instance</strong></td><td>PropTypes.objectOf()</td><td>New message()</td></tr>
</tbody>
</table>
</div><pre><code class="lang-javascript">Count.propTypes = {
  <span class="hljs-attr">basicObject</span>: PropTypes.object,
  <span class="hljs-attr">numbers</span>: PropTypes.objectOf(PropTypes.numbers),
  <span class="hljs-attr">messages</span>: PropTypes.instanceOf(Message),
  <span class="hljs-attr">contactList</span>: PropTypes.shape({
    <span class="hljs-attr">name</span>: PropTypes.string,
    <span class="hljs-attr">phone</span>: PropTypes.string,
  }),
};
</code></pre>
<h2 id="heading-advance-type-checking">Advance Type Checking</h2>
<p>There are many ways other than basic type checking we can use to check our props. This method mainly focuses on the React code rather than the data types.</p>
<h3 id="heading-how-to-check-for-a-react-component">How to Check for a React Component</h3>
<p>If you want to just check to see if a prop is a React component, you can use <strong>PropTypes.element</strong>. This is useful for ensuring that a component only ever has one child component.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Type</strong></td><td><strong>Class</strong></td><td><strong>Example</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Element</strong></td><td>PropTypes.element</td><td>&lt;Title /&gt;</td></tr>
</tbody>
</table>
</div><pre><code class="lang-javascript">Count.propTypes = {
  <span class="hljs-attr">displayEle</span>: PropTypes.element,
};
</code></pre>
<h3 id="heading-how-to-check-for-a-react-component-name">How to Check for a React Component Name</h3>
<p>Finally, we can check to see if the prop is the name of a React component by using <strong>PropTypes.elementType</strong>.</p>
<pre><code class="lang-javascript">Component.propTypes = {
  <span class="hljs-attr">as</span>: PropTypes.elementType
}
</code></pre>
<pre><code class="lang-javascript">&lt;AnotherComponent <span class="hljs-keyword">as</span>={Component} /&gt;
</code></pre>
<h2 id="heading-custom-types">Custom Types</h2>
<p>We can also have a custom validator or type checking for props but it requires an error object if the validation fails.</p>
<p>You can use this for both arrays and objects but the error object will be called for each key in the array or object. The first two arguments of the validator are the array or object itself and the current item's key.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Type</strong></td><td><strong>Class</strong></td><td><strong>Example</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Custom</strong></td><td>function(props, propName, componentName) {}</td><td>“hello”</td></tr>
<tr>
<td><strong>Custom Array</strong></td><td>PropTypes.arrayOf(function(props, propName, componentName) {})</td><td>[“hello”]</td></tr>
</tbody>
</table>
</div><pre><code class="lang-javascript">Count.propTypes = {  <span class="hljs-comment">// normal functionn</span>
  <span class="hljs-attr">customProp</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">props, propName, componentName</span>) </span>{
    <span class="hljs-keyword">if</span> (!<span class="hljs-regexp">/matchme/</span>.test(props[propName])) {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(
        <span class="hljs-string">"Invalid prop `"</span> +
          propName +
          <span class="hljs-string">"` supplied to"</span> +
          <span class="hljs-string">" `"</span> +
          componentName +
          <span class="hljs-string">"`. Validation failed."</span>
      );
    }
  },
};
</code></pre>
<pre><code class="lang-javascript">Count.propTypes = { <span class="hljs-comment">// array function</span>
  <span class="hljs-attr">customArrayProp</span>: PropTypes.arrayOf(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">
    propValue,
    key,
    componentName,
    location,
    propFullName
  </span>) </span>{
    <span class="hljs-keyword">if</span> (!<span class="hljs-regexp">/matchme/</span>.test(propValue[key])) {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(
        <span class="hljs-string">"Invalid prop `"</span> +
          propFullName +
          <span class="hljs-string">"` supplied to"</span> +
          <span class="hljs-string">" `"</span> +
          componentName +
          <span class="hljs-string">"`. Validation failed."</span>
      );
    }
  }),
};
</code></pre>
<h2 id="heading-default-proptypes">Default PropTypes</h2>
<p>Sometimes, we want to be able to set a default value for a prop. For instance, our parent component might not require a title to be passed. But we still want a title to be rendered.</p>
<p>In cases like this, we can set a default value for our title which will automatically be rendered if the title has not been passed as a prop from our parent component.</p>
<pre><code class="lang-javascript">Header.defaultProp = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"GitHub Users"</span>,
};
</code></pre>
<p>We can read more about this in the <a target="_blank" href="https://reactjs.org/docs/typechecking-with-proptypes.html">official documentation</a>.</p>
<h2 id="heading-example-time">Example Time</h2>
<p>Let’s understand how all this works with some simple React code.</p>
<p>We will make two reusable components, <strong>About.js</strong> and <strong>Count.js</strong>. The <strong>About</strong> Component is the parent component and the <strong>Count</strong> Component is the child component as shown here:</p>
<p><img src="https://lh4.googleusercontent.com/9h86z3UDdPR9zlqR19PVQFJYvAq0j2r6ZobSn1cC6Ev8JAjQo_tFRJobuIQeg0sHLc8Wha8yZp3SGQGcxrxYMA-Mo_HrCsxBrPnv6TfhqS_q9Iqioku1LaRTbx69qBsx_PueJtqe" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://lh3.googleusercontent.com/2RbGh5-GHCcP57-3GG9ysJ-9p7xFIOKRzg2Z_TzzJFObcqalPbUe_8MDe1iyckfD0rKxg6Kfcksd8V9uNx9SHV6sUr8yM37Z2NP1k7YS_e7WLIz-OXtq-jOS7DsRTjfj-C0PBPBp" alt="Image" width="600" height="400" loading="lazy"></p>
<p>What if we change the value of the age prop from a number to a string without changing its type (PropTypes)?</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Count <span class="hljs-keyword">from</span> <span class="hljs-string">"./Count"</span>;
<span class="hljs-keyword">const</span> About = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Count</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"Ateev"</span> <span class="hljs-attr">age</span>=<span class="hljs-string">"25"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> About;
</code></pre>
<p>We will receive an error in the console saying this:</p>
<p><img src="https://lh3.googleusercontent.com/NoiuFl2D3WofbIe7_CsqbNkolVLFzXyPSvvADV3LvFug2jp2oMhBXFl42Qy79e4LkGAOio5RD5rAhlUOBJEoSP3oDUuWNwxb1wCfQYdYQpWvdtDbKQQDkwt0rMSD9dlQAhXozKKC" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It clearly states that the value of the age prop passed does not match the value expected (PropTypes).</p>
<p>From the above example, it should now be clear how we can use PropTypes. You can also see how useful they are for debugging your apps when the app is too big to find the bug with just conventional methods.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>PropTypes are a great way to catch errors at run time and act as the first line of defense for your applications. They're not as type-safe as TypeScript but they're much easier to set up and work with.</p>
<p>You can also go through some of my other blogs:</p>
<ol>
<li><p><a target="_blank" href="https://tekolio.com/react-virtual-dom-explained-in-simple-words/">What do you mean by the term <strong>Virtual DOM</strong> in React</a></p>
</li>
<li><p><a target="_blank" href="https://tekolio.com/what-are-hooks-in-react/">What are Hooks in React?</a></p>
</li>
<li><p><a target="_blank" href="https://tekolio.com/how-i-made-my-portfolio-in-react/">How to make a portfolio in React</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Make a Filter Component in React ]]>
                </title>
                <description>
                    <![CDATA[ Filter components are useful on websites because they help users find the results they need quickly and easily. This is especially true if your data comes from an API, since users cannot look through everything your app has to offer. In this article,... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-a-filter-component-in-react/</link>
                <guid isPermaLink="false">66d45d98aad1510d0766b5e1</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ateev Duggal ]]>
                </dc:creator>
                <pubDate>Wed, 19 Jan 2022 16:48:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/Filter-Component-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Filter components are useful on websites because they help users find the results they need quickly and easily.</p>
<p>This is especially true if your data comes from an API, since users cannot look through everything your app has to offer.</p>
<p>In this article, we will be using dummy data that we have hardcoded and saved like an array in a separate component named <strong>Data.js.</strong></p>
<p><strong>What we'll cover here:</strong></p>
<ol>
<li><p>Getting Started</p>
</li>
<li><p>Creating our React App</p>
</li>
<li><p>Getting data from Data.js using Hooks</p>
</li>
<li><p>Working on the UI of our App</p>
</li>
<li><p>Making the Filter Component</p>
</li>
<li><p>Wrapping Up</p>
</li>
</ol>
<h2 id="heading-getting-started">Getting Started</h2>
<p>For this particular project, we will be using dummy food data which contains several key-value pairs as shown in this code:</p>
<pre><code class="lang-json">const Data = [
  {
    id: <span class="hljs-string">"1"</span>,
    title: <span class="hljs-string">"Poha"</span>,
    category: <span class="hljs-string">"Breakfast"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://c.ndtvimg.com/2021-08/loudr2go_aloo-poha_625x300_05_August_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350"</span>,
    desc: <span class="hljs-string">" Poha. Light, filling and easy to make, poha is one famous breakfast that is eaten almost everywhere in the country. And the best part is- it can be made in a number of ways. Kanda poha, soya poha, Indori poha, Nagpur Tari Poha are a few examples"</span>,
  },
  {
    id: <span class="hljs-string">"2"</span>,
    title: <span class="hljs-string">"Upma"</span>,
    category: <span class="hljs-string">"Breakfast"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350"</span>,
    desc: <span class="hljs-string">" A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour."</span>,
  },
  {
    id: <span class="hljs-string">"3"</span>,
    title: <span class="hljs-string">"Cheela"</span>,
    category: <span class="hljs-string">"Breakfast"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://c.ndtvimg.com/2019-05/1afu8vt8_weight-loss-friendly-breakfast-paneer-besan-chilla_625x300_25_May_19.jpg?im=FaceCrop,algorithm=dnn,width=620,height=350"</span>,
    desc: <span class="hljs-string">"A staple across Indian households, moong dal is widely used in a number of Indian delicacies. One such delicacy is moong dal cheela. You can also add paneer to this recipe to amp up the nutritional value and make it, even more, protein-dense"</span>,
  },
  {
    id: <span class="hljs-string">"4"</span>,
    title: <span class="hljs-string">"Channa Kulcha"</span>,
    category: <span class="hljs-string">"Lunch"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://i.ndtvimg.com/i/2015-04/chana-kulcha_625x350_41429707001.jpg"</span>,
    desc: <span class="hljs-string">"A classic dish that never goes out of style. The quintessential chana kulcha  needs only a few ingredients - cumin powder, ginger, coriander powder, carom powder, and some mango powder, which is what gives the chana its sour and tangy taste."</span>,
  },
  {
    id: <span class="hljs-string">"5"</span>,
    title: <span class="hljs-string">"Egg Curry"</span>,
    category: <span class="hljs-string">"Lunch"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://i.ndtvimg.com/i/2017-11/goan-egg-curry_620x350_41511515276.jpg"</span>,
    desc: <span class="hljs-string">"Eggs are a versatile food that can be cooked for any meal of the day. From breakfast to dinner, it can be a go-to food. Here is a mildly-spiced egg curry made with garlic, onions, a whole lot of kasuri methi, fresh cream, yogurt, and fresh coriander."</span>,
  },
  {
    id: <span class="hljs-string">"6"</span>,
    title: <span class="hljs-string">"Paneer Aachari"</span>,
    category: <span class="hljs-string">"Lunch"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://i.ndtvimg.com/i/2015-04/paneer_625x350_61429707960.jpg"</span>,
    desc: <span class="hljs-string">"Don't get intimidated by the list of ingredients because not only are already in your kitchen cabinet, but also because all they'll need is 20 minutes of your time. Chunks of cottage cheese cooked in some exciting spices, yogurt and a pinch of sugar."</span>,
  },
  {
    id: <span class="hljs-string">"7"</span>,
    title: <span class="hljs-string">"Fish Fry"</span>,
    category: <span class="hljs-string">"Dinner"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://i.ndtvimg.com/i/2015-06/indian-dinner_625x350_41434360207.jpg"</span>,
    desc: <span class="hljs-string">"Get your daily dose of perfect protein. Pieces of surmai fish marinated in garlic, cumin, fennel, curry leaves, and tomatoes are pan-fried in refined oil and served hot. This fish fry recipe has a host of delectable spices used for marination giving it a unique touch."</span>,
  },
  {
    id: <span class="hljs-string">"8"</span>,
    title: <span class="hljs-string">"Dum Alloo"</span>,
    category: <span class="hljs-string">"Dinner"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://i.ndtvimg.com/i/2015-06/indian-dinner_625x350_51434362664.jpg"</span>,
    desc: <span class="hljs-string">"Your family will thank you for this fantastic bowl of dum aloo cooked Lakhnawi style. Take some potatoes, crumbled paneer, kasuri methi, butter, onions, and some ghee."</span>,
  },
  {
    id: <span class="hljs-string">"9"</span>,
    title: <span class="hljs-string">"Malai Kofta"</span>,
    category: <span class="hljs-string">"Dinner"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://i.ndtvimg.com/i/2017-10/makhmali-kofte_620x350_51508918483.jpg"</span>,
    desc: <span class="hljs-string">"A rich gravy made of khus khus, coconut and milk that tastes best with koftas made from khoya. This velvety and creamy recipe will leave you licking your fingers. Makhmali kofte can be your go-to dish for dinner parties as this is quite different from other kofta recipes and extremely delicious."</span>,
  },
  {
    id: <span class="hljs-string">"10"</span>,
    title: <span class="hljs-string">"Malai Kofta"</span>,
    category: <span class="hljs-string">"Snaks"</span>,
    price: <span class="hljs-string">"$1"</span>,
    img: <span class="hljs-string">"https://i.ndtvimg.com/i/2017-10/makhmali-kofte_620x350_51508918483.jpg"</span>,
    desc: <span class="hljs-string">"A rich gravy made of khus khus, coconut and milk that tastes best with koftas made from khoya. This velvety and creamy recipe will leave you licking your fingers. Makhmali kofte can be your go-to dish for dinner parties as this is quite different from other kofta recipes and extremely delicious."</span>,
  },
];

export default Data;
</code></pre>
<p>Among these key-value pairs, we also have a category which will be used for filtering the results.</p>
<p>We will be using bootstrap as the CDN for this project for styling our app.</p>
<p>After this tutorial, you should know more about how to make and import components in React, how to use data dynamically, and most of all how to pass and use props between parent and child components.</p>
<h2 id="heading-how-to-create-our-react-component">How to Create our React Component</h2>
<p>It's very easy to create a React App – just go to your working directory in any of your preferred IDE’s and enter the following command in the terminal:</p>
<pre><code class="lang-php">npx create-react-app react-filter-app
</code></pre>
<p>If you are unsure how to properly set up a create-react-app project you can refer to the official guide here at <a target="_blank" href="https://create-react-app.dev/docs/getting-started/">create-react-app-dev</a>.‌‌</p>
<p>After the setup, run <code>npm start</code> in the same terminal to start the localhost:3000 where our React app will be hosted. We can also see all our changes there.</p>
<h2 id="heading-how-to-get-the-data-from-datajs-using-hooks">How to Get the data from Data.js using Hooks</h2>
<p>Now that we have successfully set up our React project, it’s time to fetch our data from Data.js and use it in our UI.</p>
<p>For this, we will first need to import our data in our <strong>App.js</strong> component and then use the useState hook for managing the state of our data.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Data <span class="hljs-keyword">from</span> <span class="hljs-string">"./Data"</span>;
<span class="hljs-keyword">import</span> Card <span class="hljs-keyword">from</span> <span class="hljs-string">"./Card"</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [item, setItem] = useState(Data);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container-fluid"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"row"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"col-12 text-center my-3 fw-bold"</span>&gt;</span>Our Menu<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Card</span> <span class="hljs-attr">item</span>=<span class="hljs-string">{item}</span> /&gt;</span> // UI Component
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-how-to-build-the-ui-part-of-our-app">How to Build the UI Part of our App</h2>
<p>Now we have our data stored in a variable which we can use freely in our App, we can work on the UI.</p>
<p>The UI will contain <a target="_blank" href="https://getbootstrap.com/docs/5.0/components/card/">bootstrap cards</a> which we'll make dynamically using the map function.</p>
<p>We will make a different component for our cards. As you can see in the above code, we have named it <strong>Card.js</strong> and have also imported it. We've also passed <strong>item</strong> as props so that we can use the data stored in the item in the card component.</p>
<p>This component will contain all our cards and the data which we will show dynamically in our App using the <strong>map function.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Card = <span class="hljs-function">(<span class="hljs-params">{ item }</span>) =&gt;</span> {            
           <span class="hljs-comment">// destructuring props</span>
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container-fluid"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"row justify-content-center"</span>&gt;</span>
          {item.map((Val) =&gt; {
            return (
              <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
                <span class="hljs-attr">className</span>=<span class="hljs-string">"col-md-4 col-sm-6 card my-3 py-3 border-0"</span>
                <span class="hljs-attr">key</span>=<span class="hljs-string">{Val.id}</span>
              &gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card-img-top text-center"</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{Val.img}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">{Val.title}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"photo w-75"</span> /&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card-body"</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card-title fw-bold fs-4"</span>&gt;</span>
                    {Val.title} <span class="hljs-symbol">&amp;nbsp;</span><span class="hljs-symbol">&amp;nbsp;</span><span class="hljs-symbol">&amp;nbsp;</span><span class="hljs-symbol">&amp;nbsp;</span>--<span class="hljs-symbol">&amp;nbsp;</span><span class="hljs-symbol">&amp;nbsp;</span>
                    {Val.price}
                  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card-text"</span>&gt;</span>{Val.desc}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
              <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            );
          })}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Card;
</code></pre>
<p>Our App with 10 cards will look this:</p>
<p><img src="https://lh5.googleusercontent.com/dcZ-3eTALXbuRdMYsDgy672KsDcuN7D--QbHOl5_2xNjocun5-zAONVPFqD8txXpVvbyKNNBV6rjEi5JAIceQzMy-K-D1OOOjWkKs59EzlRzf-VBkjwz3LxY2I8E4FBL6Bn4vrf5" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-make-the-filter-component">How to Make the Filter Component</h2>
<p>There are many ways we can use the filter components to filter out the data which the user gets from the search results. But here, we will be making buttons for this purpose which will filter out the data based on the category of that food – like breakfast, lunch, dinner, and snacks.</p>
<p>We have to make a new array that will contain only the values of the key category and display them using the map method.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// spread operator will display all the values from our category section of our data while Set will only allow the single value of each kind to be displayed</span>

  <span class="hljs-keyword">const</span> menuItems = [...new <span class="hljs-built_in">Set</span>(Data.map(<span class="hljs-function">(<span class="hljs-params">Val</span>) =&gt;</span> Val.category))];
</code></pre>
<p>We're using the <strong>spread operator</strong> here so that every value we get by displaying the above array has the same UI, and also to display all 10 categories as buttons.</p>
<p>We use the <code>Set()</code> value so that only 3 or 4 values that are unique will be displayed and also to ensure that there are no repeated values.</p>
<p>We'll create a new component for these buttons that will be dynamically displayed using the map method. But this time we will use our newly formed array as it has all the categories stored in an array and will display them only once due to <strong>Set()</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Data <span class="hljs-keyword">from</span> <span class="hljs-string">"./Data"</span>;

<span class="hljs-keyword">const</span> Buttons = <span class="hljs-function">(<span class="hljs-params">{ setItem, menuItems }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"d-flex justify-content-center"</span>&gt;</span>
        {menuItems.map((Val, id) =&gt; {
          return (
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
              <span class="hljs-attr">className</span>=<span class="hljs-string">"btn-dark text-white p-1 px-2 mx-5 btn fw-bold"</span>
              <span class="hljs-attr">key</span>=<span class="hljs-string">{id}</span>
            &gt;</span>
              {Val}
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          );
        })}
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"btn-dark text-white p-1 px-3 mx-5 fw-bold btn"</span>
          <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setItem(Data)}
        &gt;
          All
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
       <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Buttons;
</code></pre>
<p>Put this button component where you want to display the buttons. In our case, we have displayed buttons above our card component in app.js.</p>
<p><img src="https://lh5.googleusercontent.com/gX2PTVbyYQIJ-6o_WvhHZVucTJwEZhQz0moqf7GZoC68fcgC2iORyLyqRILAmhQn-e_SQy172o1_BgeLMidY69Jm3UCAXtRBiP-fNwFf50VaJPj8_54SjjlngVvCun_EaOVG-DRh" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It’s time to add a filter in these buttons so that they can filter out dishes depending upon the category.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> filterItem = <span class="hljs-function">(<span class="hljs-params">curcat</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> newItem = Data.filter(<span class="hljs-function">(<span class="hljs-params">newVal</span>) =&gt;</span> {
      <span class="hljs-keyword">return</span> newVal.category === curcat; 
            <span class="hljs-comment">// comparing category for displaying data</span>
    });
    setItem(newItem);
  };
</code></pre>
<p>The filter method filters out the data depending upon the category of that object.</p>
<p>Using the <code>onClick()</code> event handler, we can attach this filter to our buttons:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Data <span class="hljs-keyword">from</span> <span class="hljs-string">"./Data"</span>;

<span class="hljs-keyword">const</span> Buttons = <span class="hljs-function">(<span class="hljs-params">{ filterItem, setItem, menuItems }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"d-flex justify-content-center"</span>&gt;</span>
        {menuItems.map((Val, id) =&gt; {
          return (
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
              <span class="hljs-attr">className</span>=<span class="hljs-string">"btn-dark text-white p-1 px-2 mx-5 btn fw-bold"</span>
              <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> filterItem(Val)}
              key={id}
            &gt;
              {Val}
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          );
        })}
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"btn-dark text-white p-1 px-3 mx-5 fw-bold btn"</span>
          <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setItem(Data)}
        &gt;
          All
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
       <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Buttons;
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>There are many ways we can use a filter component to reduce the time our user wastes searching for ideal results in our apps.</p>
<p>There are only 10 objects in the array we have used in this app, but many times we get our data from API, where there can be tons of data. In these cases, only a single search isn't often ideal to give exact results, so we use filters to help.</p>
<p>You can see the whole code in the <a target="_blank" href="https://github.com/Ateevduggal/Filter-Menu-in-React">GitHub Repo</a>, and you can check out how these filter buttons work by going through a <a target="_blank" href="https://filter-menu-in-react.vercel.app/">live link</a> of the app.</p>
<p>You can go through my other projects as well:</p>
<ol>
<li><p><a target="_blank" href="https://tekolio.com/how-to-make-custom-pagination-in-react-js-with-hooks/">How to make a Pagination component in React using Hooks</a></p>
</li>
<li><p><a target="_blank" href="https://tekolio.com/how-to-create-a-dictionary-app-in-react/">How to make a Dictionary App in React using Hooks</a></p>
</li>
<li><p><a target="_blank" href="https://tekolio.com/how-to-host-a-react-app-on-github-pages-with-a-custom-domain/">How to host a React App on GitHub Pages with a Custom Domain</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
