<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samana Ghimire on Medium]]></title>
        <description><![CDATA[Stories by Samana Ghimire on Medium]]></description>
        <link>https://medium.com/@ghimiresamana666?source=rss-22b4396081df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2ZPGM5ibCE2gSwl0</url>
            <title>Stories by Samana Ghimire on Medium</title>
            <link>https://medium.com/@ghimiresamana666?source=rss-22b4396081df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:55:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ghimiresamana666/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Edabit Object Series]]></title>
            <link>https://medium.com/@ghimiresamana666/edabit-object-series-25dcc89e4541?source=rss-22b4396081df------2</link>
            <guid isPermaLink="false">https://medium.com/p/25dcc89e4541</guid>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Samana Ghimire]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 14:28:59 GMT</pubDate>
            <atom:updated>2024-08-03T14:28:59.584Z</atom:updated>
            <content:encoded><![CDATA[<p>Objects are an essential concept in the world of programming. Mapping an array of objects to reducing an array to object, all starts with the basics. I am therefore initiating this object series from edabit questions every Saturday for beginners.</p><p>Please be aware that there is no one right method to approach or solve the problem. Also, the answers are based on my approach and perspective. Don’t hesitate to share your own solutions as well. Now let’s get going…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fy9XCVEKx02Q3tyHSD5%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fy9XCVEKx02Q3tyHSD5%2Fgiphy.gif%3Fcid%3D790b761132sw21d966l51kyhd7w7805b0xpm923teugcr74e%26ep%3Dv1_gifs_search%26rid%3Dgiphy.gif%26ct%3Dg&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExc3phNTd0NnJpMWQ1azVybnB0bmd0MHpoYzh6Ynh6M3Jmdjlpd3UxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fy9XCVEKx02Q3tyHSD5%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/1583d238b0c06f4a5591b5d1d7f85542/href">https://medium.com/media/1583d238b0c06f4a5591b5d1d7f85542/href</a></iframe><p><strong>Question: Sort Authors Last Names Alphabetically</strong></p><p><a href="https://edabit.com/challenge/vtFsh5CzFep6b9gDf">https://edabit.com/challenge/vtFsh5CzFep6b9gDf</a></p><p>We are given an array of objects with book name, rating and author’s name. The objects must be arranged alphabetically according to the last name of the author. Here’s an illustration of what’s expected.</p><pre>sortByLastName([<br>  { name: &quot;Harry Potter&quot;, rating: &quot;8+&quot;, author: &quot;Joanne Rowling&quot; },<br>  { name: &quot;Warcross&quot;, rating: &quot;13+&quot;, author: &quot;Marie Lu&quot; },<br>  { name: &quot;The Hunger Games&quot;, rating: &quot;12+&quot;, author: &quot;Suzanne Collins&quot; },<br>]) ➞ [<br>  { name: &quot;The Hunger Games&quot;, rating: &quot;12+&quot;, author: &quot;Suzanne Collins&quot; },<br>  { name: &quot;Warcross&quot;, rating: &quot;13+&quot;, author: &quot;Marie Lu&quot; },<br>  { name: &quot;Harry Potter&quot;, rating: &quot;8+&quot;, author: &quot;Joanne Rowling&quot; },<br>]</pre><p>The example above shows us that Suzzanne Collins is the first object with the name, followed by Marie Lu and Joanne Rowling. The reason for this is that C comes before L and R in the alphabet, hence at first. Let’s go through this problem and then understand gradually.</p><p><strong>Solution</strong></p><pre>const sortByLastName=(books)=&gt;{<br> const lastNames=books.map(book=&gt;book.author.split(&quot; &quot;)[1]).sort();<br> return books.map((book,index)=&gt;{<br>  const sortedName=lastNames[index];<br>  return books.find(book=&gt;book.author.endsWith(sortedName));<br> })<br>}</pre><p><strong>Step1:</strong> We generated the last names, which are arranged alphabetically, by mapping the books array.</p><pre>const lastNames=books.map(book=&gt;book.author.split(&quot; &quot;)[1]).sort();<br><br>// [ &#39;Collins&#39;, &#39;Lu&#39;, &#39;Rowling&#39; ]</pre><p><strong>Step 2:</strong> Once more, we mapped the books array and used the lastNames array’s index to get the last name.</p><pre>return books.map((book,index)=&gt;{<br>  const sortedName=lastNames[index];<br>})<br>/* <br>Collins=&gt;lastNames[0]<br>Lu=&gt;lastNames[1]<br>Rowling=&gt;lastNames[2] */</pre><p><strong>Step 3:</strong> Now, the item whose final name ends with the sortedName has to be retrieved and returned.</p><pre> return books.find(book=&gt;book.author.endsWith(sortedName));<br><br>//first iteration<br>{ name: &#39;The Hunger Games&#39;, rating: &#39;12+&#39;, author: &#39;Suzanne Collins&#39; },<br><br>//second iteration<br>{ name: &#39;Warcross&#39;, rating: &#39;13+&#39;, author: &#39;Marie Lu&#39; }<br><br>//final iteration<br>{ name: &#39;Harry Potter&#39;, rating: &#39;8+&#39;, author: &#39;Joanne Rowling&#39; }</pre><p>Since we are mapping the array and returning it, the outcome is as follows:</p><pre>[{ name: &#39;The Hunger Games&#39;, rating: &#39;12+&#39;, author: &#39;Suzanne Collins&#39; }, { name: &#39;Warcross&#39;, rating: &#39;13+&#39;, author: &#39;Marie Lu&#39; }, { name: &#39;Harry Potter&#39;, rating: &#39;8+&#39;, author: &#39;Joanne Rowling&#39; }]</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F229OX0vSVNys10AZnS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExam0wNXJ6c2E1dTh1bHAybmJrd20xNG84dW0wdG5pNXlxcHBzZzlubSZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2F229OX0vSVNys10AZnS%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYjlyemdncmVvZXdjZGZtajZocTdnM3ozOXFqbGlyaW0wYnJmc2VweCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F229OX0vSVNys10AZnS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/319fd8d17c91af3736cc4dfd86e43485/href">https://medium.com/media/319fd8d17c91af3736cc4dfd86e43485/href</a></iframe><p>I hope it was able to teach you something. Please explore further, and happy coding!!</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map() - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find">Array.prototype.find() - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith">String.prototype.endsWith() - JavaScript | MDN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25dcc89e4541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PropTypes in react]]></title>
            <link>https://medium.com/@ghimiresamana666/proptypes-in-react-538375e611ee?source=rss-22b4396081df------2</link>
            <guid isPermaLink="false">https://medium.com/p/538375e611ee</guid>
            <category><![CDATA[typecheck]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Samana Ghimire]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 10:46:02 GMT</pubDate>
            <atom:updated>2022-08-31T10:46:02.772Z</atom:updated>
            <content:encoded><![CDATA[<p>This article provides an example of how PropTypes implements type checking in a React application. Let’s begin.</p><p><strong>What is PropTypes?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FMsWnkCVSXz73i%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FMsWnkCVSXz73i%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FMsWnkCVSXz73i%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f71f6685dad207cfe69932fe3dd5520/href">https://medium.com/media/0f71f6685dad207cfe69932fe3dd5520/href</a></iframe><p>PropTypes is a method for guaranteeing that the props we are receiving are of the correct datatype. Props allow us to send data to any component.</p><p><strong>To</strong> <strong>install:</strong></p><p>Using <strong>NPM</strong></p><pre>npm install --save prop-types</pre><p>Using <strong>Yarn</strong></p><pre>yarn add prop-types</pre><p><strong>To import:</strong></p><pre>import PropTypes from &quot;prop-types&quot;;</pre><blockquote>For information on propTypes, Please check the link below</blockquote><blockquote><a href="https://reactjs.org/docs/typechecking-with-proptypes.html">https://reactjs.org/docs/typechecking-with-proptypes.html</a></blockquote><p>We are styling it as well and for that, we’re using <strong>Material UI</strong>.</p><p>Using<strong> NPM</strong></p><pre>npm install <a href="http://twitter.com/mui/material">@mui/material</a> <a href="http://twitter.com/emotion/react">@emotion/react</a> <a href="http://twitter.com/emotion/styled">@emotion/styled</a></pre><p>Using <strong>Yarn</strong></p><pre>yarn add <a href="http://twitter.com/mui/material">@mui/material</a> <a href="http://twitter.com/emotion/react">@emotion/react</a> <a href="http://twitter.com/emotion/styled">@emotion/styled</a></pre><blockquote>Visit the following URL for more details about Material UI. <a href="https://mui.com/material-ui/getting-started/overview/">https://mui.com/material-ui/getting-started/overview/</a></blockquote><p>Let’s start working on our files now!</p><p>Make a file called <strong>ComponentA.js</strong> in the components subdirectory of the src directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*ctT23m6lZg8JOlShbBw5qA.png" /><figcaption>component folder structure</figcaption></figure><p>Create a file called <strong>data.js</strong> in the same directory as App.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*ulmqIinPuR2TPlYSPznpsw.png" /></figure><p><strong>data.js</strong></p><pre>export const person = [<br>    {<br>        id: 1,<br>        name: &quot;John&quot;,<br>        city: &quot;New York&quot;,<br>        age: 25,<br>        isMarried: false,<br>        image: &quot;<a href="https://i.picsum.photos/id/1005/5760/3840.jpg?hmac=2acSJCOwz9q_dKtDZdSB-OIK1HUcwBeXco_RMMTUgfY">https://i.picsum.photos/id/1005/5760/3840.jpg?hmac=2acSJCOwz9q_dKtDZdSB-OIK1HUcwBeXco_RMMTUgfY</a>&quot;,<br>    },<br>    {<br>        id: 2,<br>        name: &quot;Larry&quot;,<br>        city: &quot;California&quot;,<br>        age: 21,<br>        isMarried: false,<br>        image: &quot;<a href="https://i.picsum.photos/id/22/4434/3729.jpg?hmac=fjZdkSMZJNFgsoDh8Qo5zdA_nSGUAWvKLyyqmEt2xs0">https://i.picsum.photos/id/22/4434/3729.jpg?hmac=fjZdkSMZJNFgsoDh8Qo5zdA_nSGUAWvKLyyqmEt2xs0</a>&quot;,<br>    },<br>    {<br>        id: 3,<br>        name: &quot;Amara&quot;,<br>        city: &quot;Malibu&quot;,<br>        age: 35,<br>        isMarried: true,<br>        image: &quot;<a href="https://i.picsum.photos/id/1027/2848/4272.jpg?hmac=EAR-f6uEqI1iZJjB6-NzoZTnmaX0oI0th3z8Y78UpKM">https://i.picsum.photos/id/1027/2848/4272.jpg?hmac=EAR-f6uEqI1iZJjB6-NzoZTnmaX0oI0th3z8Y78UpKM</a>&quot;,<br>    },<br>];</pre><p>In real projects, we’ll use an API to get data, but let’s suppose for now that it will be kept in a constant called person. Although the data structure is simple in this case, it may be complex depending on the project we are working on. We exported it so that it can be used throughout our app.</p><p><strong>App.js</strong></p><pre>import &quot;./styles.css&quot;;<br>import { person } from &quot;./data.js&quot;;<br>import ComponentA from &quot;./components/ComponentA&quot;;<br>export default function App() {<br>    return (<br>        &lt;div className=&quot;App&quot;&gt;<br>            &lt;ComponentA info={person} /&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>The previously described data was imported and then made available using info props.</p><p><strong>ComponentA.js</strong></p><pre>import React from &quot;react&quot;;<br>import { Chip, Card, CardMedia, CardContent, Typography, Grid } from &quot;<a href="http://twitter.com/mui/material">@mui/material</a>&quot;;<br>import PropTypes from &quot;prop-types&quot;;<br>const ComponentA = ({ info }) =&gt; {<br>    return (<br>        &lt;&gt;<br>            &lt;h1&gt;Following are some extremely talented people&lt;/h1&gt;<br>            &lt;Grid item container spacing={2} justifyContent=&quot;center&quot; alignItems=&quot;center&quot; sx={{ width: &quot;800px&quot;, maxWidth: &quot;100%&quot;, margin: &quot;0 auto&quot; }}&gt;<br>                {info.map((data) =&gt; {<br>                    const mariatalStatus = data.isMarried ? &quot;married&quot; : &quot;single&quot;;<br>                    return (<br>                        &lt;Grid item md={4} sm={6} xs={12} key={data.id}&gt;<br>                            &lt;Card&gt;<br>                                &lt;CardMedia component=&quot;img&quot; height=&quot;140&quot; image={data.image} alt=&quot;image&quot; /&gt;<br>                                &lt;CardContent&gt;<br>                                    &lt;Typography gutterBottom variant=&quot;h5&quot; component=&quot;div&quot;&gt;<br>                                        {data.name}<br>                                    &lt;/Typography&gt;<br>                                    &lt;Typography variant=&quot;body2&quot; color=&quot;text.secondary&quot;&gt;<br>                                        {data.age}, {data.city}<br>                                    &lt;/Typography&gt;<br>                                    &lt;Chip label={mariatalStatus} color=&quot;success&quot; variant=&quot;outlined&quot; /&gt;<br>                                &lt;/CardContent&gt;<br>                            &lt;/Card&gt;<br>                        &lt;/Grid&gt;<br>                    );<br>                })}<br>            &lt;/Grid&gt;<br>        &lt;/&gt;<br>    );<br>};<br>export default ComponentA;<br>ComponentA.propTypes = {<br>  info: PropTypes.arrayOf(<br>    PropTypes.objectOf(<br>      PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool])<br>    )<br>  )<br>};</pre><p>Let’s try to determine what is happening.</p><p>As we now have access to the props data, we can use it in our file to display the data that is contained inside. The Material UI components are used to give our app a little cleaner appearance.</p><p>PropTypes have allowed us to specify the types of data that we expect to be used as props.</p><blockquote>PropTypes.arrayOf()=<strong>array</strong> data type</blockquote><blockquote>PropTypes.objectOf()=<strong>object</strong> data type</blockquote><blockquote>PropTypes.oneOfType([])=<strong>object</strong> data type(what type of values are expected inside that object)</blockquote><blockquote>PropTypes.number()=<strong>number</strong> data type</blockquote><blockquote>PropTypes.string()=<strong>string</strong> data type</blockquote><blockquote>PropTypes.bool()=<strong>boolean</strong> data type</blockquote><p>We can therefore state that in our code, we are expecting an array of an object whose elements are of the data types string, numeric, or boolean.</p><p>We see the following as a result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*pp502HH5XiSvnaXgWRuQhA.png" /><figcaption>Images from<a href="https://picsum.photos/images"> </a><a href="https://picsum.photos/images">https://picsum.photos/images</a></figcaption></figure><blockquote>source code: <a href="https://codesandbox.io/s/peaceful-sea-216lyd?file=/src/App.js">https://codesandbox.io/s/peaceful-sea-216lyd?file=/src/App.js</a></blockquote><p>Now, let’s correct our data. We adjusted the city field from a string to a number.</p><pre>city: 121,</pre><p>Try out our code. To our delight, it keeps running and displays our output on the screen. Why???</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*s2Nc4dK-j_Kg5fIzHcWdIg.png" /><figcaption>Output after changing the city name to number</figcaption></figure><p>Let’s start by taking a look at the PropTypes declaration.</p><pre>ComponentA.propTypes = {<br>  info: PropTypes.arrayOf(<br>    PropTypes.objectOf(<br>      PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool])<br>    )<br>  )<br>};</pre><p>Here, we specify that the object’s values must be of one of the following data types: number, string, or boolean. 121 is valid since it is a number. What if, on the other hand, we wanted the city name to be a string only? How are we going to do that?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FmRh4cLIYhrs9G%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FmRh4cLIYhrs9G%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FmRh4cLIYhrs9G%2F200.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d96418d3d631625ae77b9dce93c5fa/href">https://medium.com/media/68d96418d3d631625ae77b9dce93c5fa/href</a></iframe><p>By using PropTypes.shape(), we can accomplish this. This verifies an object’s type.</p><pre>ComponentA.propTypes = {<br>    info: PropTypes.arrayOf(<br>        PropTypes.shape({<br>            id: PropTypes.number,<br>            name: PropTypes.string,<br>            city: PropTypes.string,<br>            age: PropTypes.number,<br>            isMarried: PropTypes.bool,<br>            image: PropTypes.string,<br>        })<br>    ),<br>};</pre><p>We will now see a warning on the console if we execute the code again. It is because we have specified that the city will only have a value of string type. Any other value than string results in this warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*Ig28JL2lK6rxlk5Z9_7pIQ.png" /><figcaption>warning due to invalid datatype</figcaption></figure><p>Another scenario is that we might implement the above code but fail to include the PropTypes number.</p><pre>ComponentA.propTypes = {<br>  info: PropTypes.arrayOf(<br>    PropTypes.objectOf(<br>      PropTypes.oneOfType([PropTypes.string, PropTypes.bool])<br>    )<br>  )<br>};</pre><p>We do see what we were looking for on the screen. But a warning appears on the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*b0Pn11kVnkdrlHe4dbaMqw.png" /><figcaption>warning due to missed number PropType validation</figcaption></figure><p>Since we passed a value that is of the number data type when only the string or boolean data types were expected, we get this warning.</p><p>We were successful in achieving our objectives so we can ignore this warning as the screen shows no errors at all. It is, however, a bad practice.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FM91dKHqpR5f0Jf75wa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FM91dKHqpR5f0Jf75wa%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FM91dKHqpR5f0Jf75wa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ea8a89915eca14cf21da5c5daf2b0ab/href">https://medium.com/media/8ea8a89915eca14cf21da5c5daf2b0ab/href</a></iframe><p>So did you learn anything new?? Please let me know in the comments. Have a great day and happy coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=538375e611ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication and Authorization in react]]></title>
            <link>https://medium.com/@ghimiresamana666/authentication-and-authorization-in-react-8fc76a496ba0?source=rss-22b4396081df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc76a496ba0</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Samana Ghimire]]></dc:creator>
            <pubDate>Thu, 18 Aug 2022 11:32:30 GMT</pubDate>
            <atom:updated>2022-08-18T11:32:30.808Z</atom:updated>
            <content:encoded><![CDATA[<p>We will make advantage of authentication and authorization functionalities for our react app in this tutorial. Let’s begin…</p><p><strong>What is authentication?</strong></p><p>Authentication is the process of confirming a user’s identity using provided credentials. It is common to start by making sure the user is legitimate.</p><p><strong>What is authorization?</strong></p><p>Authorization is the security procedure used to determine the rights or access levels of user-clients. It is standard procedure to check whether an authenticated user has access to or authorization to do a task.</p><p>Let’s work on organizing our files and folders.</p><p>Make a <strong>components</strong> folder under src.<br>Then make the following files: <strong>Unauthorized.js</strong>, <strong>Navbar.js</strong>, <strong>Profile.js</strong>, <strong>Extra.js</strong>, <strong>Home.js</strong>, <strong>About.js</strong>, and <strong>Extra.js</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*gAGO21GCOZGKzHS52Nphbw.png" /><figcaption>creation of files inside the components directory</figcaption></figure><p>Since we will be using the <strong>react-router</strong> package, let’s install it by using the following command.</p><p>Using<strong> NPM</strong></p><pre>npm install react-router-dom@6</pre><p>Using<strong> Yarn</strong></p><pre>yarn add react-router-dom@6</pre><blockquote>For more information about react-router visit: <a href="https://reactrouter.com/docs/en/v6/getting-started/overview">https://reactrouter.com/docs/en/v6/getting-started/overview</a></blockquote><p>Let’s make a new folder called <strong>routes</strong>.</p><p>Make the following files: <strong>Authentication.js</strong>, <strong>Authorization.js,</strong> and <strong>RoutePath.js.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*-knlKcKqLe08eLkdUfkUqA.png" /><figcaption>creation of files inside routes directory</figcaption></figure><p>Let’s add two additional folders with the names <strong>permissions</strong> and <strong>provider</strong>, along with the files <strong>permissions.js </strong>and <strong>authprovider.js</strong>, respectively.</p><p>This marks the conclusion of our folder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*IrWs-xDMFTR8btxlBi9SBw.png" /><figcaption>Folder structure</figcaption></figure><p>We won’t use complex code or pay attention to design because our sole objective is to understand how authentication and authorization can be implemented.</p><p>Start making changes to our files now!!!</p><p><strong>Permissions.js</strong></p><pre>const PERMISSIONS = {<br>    CAN_VIEW_ABOUT: &quot;view_about&quot;,<br>    CAN_VIEW_EXTRA: &quot;view_extra&quot;,<br>};<br>export default PERMISSIONS;</pre><p>To prevent unauthorized users from accessing certain data, we created permissions.</p><p><strong>AuthProvider.js</strong></p><pre>import React, { createContext, useContext, useState } from &quot;react&quot;;<br>import { useNavigate, useLocation } from &quot;react-router-dom&quot;;</pre><pre>const AuthContext = createContext(null);<br>export const AuthProvider = ({ children }) =&gt; {<br>    const navigate = useNavigate();<br>    const location = useLocation();<br>    const redirectPath = location.state?.path || &quot;/profile&quot;;<br>    const [user, setUser] = useState({<br>        username: &quot;&quot;,<br>        permissions: [],<br>    });<br>    const login = (user) =&gt; {<br>        if (user === &quot;admin&quot;) {<br>            setUser({ username: user, permissions: [&quot;view_extra&quot;] });<br>        } else {<br>            setUser({ username: user, permissions: [&quot;view_about&quot;] });<br>        }<br>        navigate(redirectPath, { replace: true });<br>    };<br>    const logout = () =&gt; {<br>        setUser({ username: &quot;&quot;, permissions: [] });<br>    };<br>    return &lt;AuthContext.Provider value={{ user, login, logout }}&gt;{children}&lt;/AuthContext.Provider&gt;;<br>};<br>export const useAuth = () =&gt; {<br>    return useContext(AuthContext);<br>};</pre><p>In order to store the currently logged-in user and the issued permission, we created a state variable object called user.</p><p>The <strong>login()</strong> accepts the user parameter. If the user is an admin, the permission assigned would be view_extra; otherwise, it would be view_about. The username would be the same as the user. After that, we’ll navigate to the route we tried to use to view the page or to the profile page.</p><p>The user variable is cleared out by the <strong>logout ()</strong>.</p><p>We built a context and sent values user, login, and logout as props through the provider. Throughout our app, we may access them everywhere.</p><p><strong>Authentication.js</strong></p><pre>import React from &quot;react&quot;;<br>import { useAuth } from &quot;../provider/AuthProvider&quot;;<br>import { Navigate, useLocation } from &quot;react-router-dom&quot;;<br>const Authentication = ({ children }) =&gt; {<br>    const { user } = useAuth();<br>    const location = useLocation();<br>    if (!user.username) {<br>        return &lt;Navigate to=&quot;/login&quot; state={{ path: location.pathname }} /&gt;;<br>    }<br>    return children;<br>};</pre><pre>export default Authentication;</pre><p>Through useAuth(), we were able to access the user object. If there is no username property, it is assumed that we are not logged in, and we are sent to the login page. In any other case, the requested page will be displayed.</p><p><strong>Authorization.js</strong></p><pre>import React from &quot;react&quot;;<br>import { Navigate, useLocation, Outlet } from &quot;react-router-dom&quot;;<br>import Unauthorized from &quot;../components/Unauthorized&quot;;<br>import { useAuth } from &quot;../provider/AuthProvider&quot;;<br>const Authorization = ({ permissions }) =&gt; {<br>    const { user } = useAuth();<br>    const location = useLocation();<br>    if (user.username) {<br>        const userpermission = user.permissions;<br>        const isAllowed = permissions.some((allowed) =&gt; userpermission.includes(allowed));<br>        return isAllowed ? &lt;Outlet /&gt; : &lt;Unauthorized /&gt;;<br>    }<br>    return &lt;Navigate to=&quot;/login&quot; state={{ path: location.pathname }} replace /&gt;;<br>};</pre><pre>export default Authorization;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F8dGP6ex3Es45W%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F8dGP6ex3Es45W%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F8dGP6ex3Es45W%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d81763e120f0542d602e08754337e29/href">https://medium.com/media/9d81763e120f0542d602e08754337e29/href</a></iframe><p>Let’s attempt to decipher the code piece by piece.</p><p>Have you kept in mind that we have our permission set according to the username? Through the user who is now logged in, we can now access that privilege.</p><p>Obtaining permission depends on whether the user is logged in. We want to determine whether the user who is currently logged in has been granted permission through the parent component. If the user is authorized, the component renders the &lt;Outlet /&gt; (Children Route); if not, it returns an Unauthorized component.</p><p>The login page is displayed if the user is not already logged in.</p><p>in <strong>Routepath.js</strong></p><pre>&lt;Route element={&lt;Authorization permissions={[PERMISSIONS.CAN_VIEW_ABOUT]} /&gt;}&gt;<br>    &lt;Route path=&quot;about&quot; element={&lt;About /&gt;} /&gt;<br>&lt;/Route&gt;;</pre><p>The user can visit the about page with CAN_VIEW_ABOUT thanks to the Authorization component in &lt;Route&gt; passed as element with permissions.</p><p>in <strong>Authorization.js</strong></p><pre>const Authorization = ({ permissions }) =&gt; {}</pre><p>The prop permissions have been handed to us by the RoutePath Component, which in this case is a parent, so we may now access them.</p><pre>const { user } = useAuth();</pre><p>Through useAuth(), we can access the current user.</p><pre>if (user.username) {<br>    const userpermission = user.permissions;<br>    const isAllowed = permissions.some((allowed) =&gt; userpermission.includes(allowed));<br>    return isAllowed ? &lt;Outlet /&gt; : &lt;Unauthorized /&gt;;<br>}<br>return &lt;Navigate to=&quot;/login&quot; state={{ path: location.pathname }} replace /&gt;;</pre><p>A user can access the username and permission property if they are logged in. We must determine whether the authorization we have granted includes permission from the logged-in user.</p><pre>const isAllowed = permissions.some((allowed) =&gt; userpermission.includes(allowed));</pre><p>If the user has permission, the (Children Route) is rendered; otherwise, an Unauthorized component is returned.<br>The login page is displayed if the user isn’t already logged in.</p><p><strong>About.js</strong></p><pre>import React from “react”;</pre><pre>const About = () =&gt; {<br> return &lt;div&gt;About Page&lt;/div&gt;;<br>};</pre><pre>export default About;</pre><p><strong>Extra.js</strong></p><pre>import React from &quot;react&quot;;</pre><pre>const Extra = () =&gt; {<br>    return &lt;div&gt;Extra Page&lt;/div&gt;;<br>};</pre><pre>export default Extra;</pre><p><strong>Home.js</strong></p><pre>import React from &quot;react&quot;;</pre><pre>const Home = () =&gt; {<br>    return &lt;div&gt;Home Page&lt;/div&gt;;<br>};</pre><pre>export default Home;</pre><p><strong>Login.js</strong></p><pre>import React, { useState } from &quot;react&quot;;<br>import { useAuth } from &quot;../provider/AuthProvider&quot;;<br>const Login = () =&gt; {<br>    const [user, setUser] = useState(null);<br>    const { login } = useAuth();<br>    const navigate = useNavigate();<br>    const location = useLocation();<br>    const redirectPath = location.state?.path || &quot;&quot;;</pre><pre>const handleLogin = () =&gt; {<br>        login(user);<br>    };<br>    return (<br>        &lt;&gt;<br>            &lt;h1&gt;Login Page&lt;/h1&gt;<br>            &lt;label&gt;Name&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; onChange={(e) =&gt; setUser(e.target.value)} /&gt;<br>            &lt;button type=&quot;submit&quot; onClick={handleLogin}&gt;<br>                Login<br>            &lt;/button&gt;<br>        &lt;/&gt;<br>    );<br>};</pre><pre>export default Login;</pre><p>We created a user state variable and added an input field. The data entered in the input box will be kept for the user and sent as an argument when logging in.</p><p><strong>Navbar.js</strong></p><pre>import React from &quot;react&quot;;<br>import { NavLink } from &quot;react-router-dom&quot;;<br>import { useAuth } from &quot;../provider/AuthProvider&quot;;<br>export const Navbar = () =&gt; {<br>    const { user } = useAuth();<br>    return (<br>        &lt;nav&gt;<br>            &lt;NavLink to=&quot;/&quot;&gt;Home&lt;/NavLink&gt;<br>            &lt;NavLink to=&quot;/about&quot;&gt;About&lt;/NavLink&gt;<br>            {user.username &amp;&amp; &lt;NavLink to=&quot;/profile&quot;&gt;Profile&lt;/NavLink&gt;}<br>            {!user.username &amp;&amp; &lt;NavLink to=&quot;/login&quot;&gt;Login&lt;/NavLink&gt;}<br>            &lt;NavLink to=&quot;/extra&quot;&gt;Extra&lt;/NavLink&gt;<br>        &lt;/nav&gt;<br>    );<br>};</pre><p>To make it simpler to move between different routes, we added a navbar. The profile link is available for logged-in users, but the login link will be visible for those who have not yet authenticated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*hna41qesJTGEIQBDkBe39Q.png" /><figcaption>For unauthenticated users</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*jx63lmbBv9Q_oE_4w7kcYg.png" /><figcaption>For logged-in user</figcaption></figure><p><strong>Profile.js</strong></p><pre>import React from &quot;react&quot;;<br>import { useAuth } from &quot;../provider/AuthProvider&quot;;<br>const Profile = () =&gt; {<br>    const { user, logout } = useAuth();<br>    const logoutHandler = () =&gt; {<br>        logout();<br>    };<br>    return (<br>        &lt;&gt;<br>            &lt;h1&gt;Welcome {user.username}&lt;/h1&gt;<br>            &lt;button type=&quot;submit&quot; onClick={logoutHandler}&gt;<br>                Logout<br>            &lt;/button&gt;<br>        &lt;/&gt;<br>    );<br>};</pre><pre>export default Profile;</pre><p>We used useAuth() to access <strong>user</strong> and <strong>logout()</strong>. We added a logout button to handle logout operations and displayed the username of the user who is presently logged in.</p><p><strong>Unauthorized.js</strong></p><pre>import React from “react”;</pre><pre>const Unauthorized = () =&gt; {<br> return &lt;div&gt;You donot have permission to view this page&lt;/div&gt;;<br>};</pre><pre>export default Unauthorized;</pre><p><strong>RoutePath.js</strong></p><pre>import React from &quot;react&quot;;<br>import { Routes, Route } from &quot;react-router-dom&quot;;<br>import Home from &quot;../components/Home&quot;;<br>import About from &quot;../components/About&quot;;<br>import Login from &quot;../components/Login&quot;;<br>import Profile from &quot;../components/Profile&quot;;<br>import Authentication from &quot;./Authentication&quot;;<br>import Authorization from &quot;./Authorization&quot;;<br>import PERMISSIONS from &quot;../permissions/Permissions&quot;;<br>import Extra from &quot;../components/Extra&quot;;<br>const RoutePath = () =&gt; {<br>    return (<br>        &lt;Routes&gt;<br>            &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>            &lt;Route element={&lt;Authorization permissions={[PERMISSIONS.CAN_VIEW_ABOUT]} /&gt;}&gt;<br>                &lt;Route path=&quot;about&quot; element={&lt;About /&gt;} /&gt;<br>            &lt;/Route&gt;<br>            &lt;Route<br>                path=&quot;profile&quot;<br>                element={<br>                    &lt;Authentication&gt;<br>                        &lt;Profile /&gt;<br>                    &lt;/Authentication&gt;<br>                }<br>            /&gt;<br>            &lt;Route element={&lt;Authorization permissions={[PERMISSIONS.CAN_VIEW_EXTRA]} /&gt;}&gt;<br>                &lt;Route path=&quot;extra&quot; element={&lt;Extra /&gt;} /&gt;<br>            &lt;/Route&gt;<br>            &lt;Route path=&quot;login&quot; element={&lt;Login /&gt;} /&gt;<br>        &lt;/Routes&gt;<br>    );<br>};</pre><pre>export default RoutePath;</pre><p>In the <strong>&lt;Routes&gt;</strong> component, we encapsulated our routes.</p><pre>&lt;Route<br>    path=&quot;profile&quot;<br>    element={<br>        &lt;Authentication&gt;<br>            &lt;Profile /&gt;<br>        &lt;/Authentication&gt;<br>    }<br>/&gt;;</pre><p>We encapsulated the route with the <strong>&lt;Authentication&gt;</strong> component because it requires authentication before access.</p><pre>&lt;Route element={&lt;Authorization permissions={[PERMISSIONS.CAN_VIEW_EXTRA]} /&gt;}&gt;<br>    &lt;Route path=&quot;extra&quot; element={&lt;Extra /&gt;} /&gt;<br>&lt;/Route&gt;;</pre><p>Additionally, we passed <strong>&lt;Authorization&gt;</strong> as the route element for the route that required authorization along with the permissions, which served as a wrapper for the child route. Only the user with access, in this case admin, may see the &lt;Extra /&gt; component.</p><p>Following is the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8u590rCf0gvThvAdNOAqoQ.gif" /></figure><p>So, did you pick up anything new? Feel free to alter and experiment with. Happy coding!</p><blockquote><a href="https://codesandbox.io/s/jovial-glade-xjh7hb?file=/src/App.js">https://codesandbox.io/s/jovial-glade-xjh7hb?file=/src/App.js</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc76a496ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useContext react hook]]></title>
            <link>https://medium.com/@ghimiresamana666/usecontext-react-hook-5edaeb8ff1a9?source=rss-22b4396081df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5edaeb8ff1a9</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[usecontext]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Samana Ghimire]]></dc:creator>
            <pubDate>Sun, 14 Aug 2022 06:02:59 GMT</pubDate>
            <atom:updated>2022-08-17T04:23:26.590Z</atom:updated>
            <content:encoded><![CDATA[<p>This article discusses <strong>useContext() </strong>and how can we use it in our react project. Let’s get started.</p><p>You might have come across a situation where you need to pass data from parent to child component. To achieve this you would pass the data as props from the parent.</p><p>Example: We have a parent component A and child component B. We need to pass a prop called color from parent to child.</p><p><strong>Component A(Parent)</strong></p><pre>import React from &quot;react&quot;;<br>import ComponentB from &quot;./ComponentB&quot;;<br>const ComponentA = () =&gt; {<br>    return (<br>        &lt;&gt;<br>            &lt;h4&gt;Hello I am component A&lt;/h4&gt;<br>            &lt;ComponentB color=&quot;red&quot; /&gt;<br>        &lt;/&gt;<br>    );<br>};<br>export default ComponentA;</pre><p><strong>Component B(Child)</strong></p><pre>import React from &quot;react&quot;;<br>const ComponentB = ({ color }) =&gt; {<br>    return (<br>        &lt;&gt;<br>            &lt;h4&gt;Hello I am component B with {color} color.&lt;/h4&gt;<br>        &lt;/&gt;<br>    );<br>};<br>export default ComponentB;</pre><p><strong>App.js</strong></p><pre>import React from &quot;react&quot;;<br>import ComponentA from &quot;./ComponentA&quot;;<br>const App = () =&gt; {<br>    return (<br>        &lt;&gt;<br>            &lt;ComponentA /&gt;<br>        &lt;/&gt;<br>    );<br>};</pre><pre>export default App;</pre><p>Well, it was easy. How about passing data from Parent Component to Component 6?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*QZ4BLfWT68gXM85wRdSBbA.jpeg" /></figure><p>You might think okay this can be done the same way as before i.e passing props from parent to child component 6. The steps involved would be:</p><ul><li>Passing data from the parent component to Component 1.</li><li>Passing data from Component 1 to Component 4.</li><li>Passing data from Component 4 to Component 6.</li></ul><p>Now imagine the component tree nesting down up to Component 100 or so on. Would you keep passing on props the same way?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FiAYupOdWXQy5a4nVGk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FiAYupOdWXQy5a4nVGk%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FiAYupOdWXQy5a4nVGk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/f614760e1de5805663b877570d6811aa/href">https://medium.com/media/f614760e1de5805663b877570d6811aa/href</a></iframe><p>This process of passing props from a higher-level component to a lower-level component is called prop drilling. In our scenario, even the components that do not require the data still have to access it and pass those as props because their children need them. It is confusing and time-consuming.</p><h3><strong>useContext hook to the rescue…</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5BaJ6438Qp6RJQRRQn%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5BaJ6438Qp6RJQRRQn%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F5BaJ6438Qp6RJQRRQn%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="199" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a2a2bf88640d48d280df4917c294f96/href">https://medium.com/media/3a2a2bf88640d48d280df4917c294f96/href</a></iframe><p>Before diving into useContext, let’s talk about hooks. Hooks are nothing but functional components that can handle state-based logic. In simple words, they are just a function to handle some state-based reusable operations.</p><p><strong>What is the useContext hook?</strong></p><p>useContext()is a method to provide data no matter how deeply nested the components are without having to pass props. Hence no prop-drilling!!!</p><p><strong>When to use it?</strong></p><p>We can use context if we want some data or state to be globally accessed throughout the component hierarchy without having to pass props to each level.</p><p><strong>How to use it?</strong></p><p>We need a context(can be global states or global data that needs to be accessed/managed throughout our app), provider (to provide the context), and consumer (to consume that context)</p><p>There are 3 simple steps.</p><ol><li>Step one: Create the context</li><li>Step two: Provide the context</li><li>Step three: Consume the context</li></ol><p>Let’s go into each step slowly.</p><p>Create a file called <strong>ContextProvider.js </strong>and copy the contents below.</p><p><strong>ContextProvider.js</strong></p><pre>import React, { createContext } from &quot;react&quot;;<br>export const DataContext = createContext(null);<br>const ContextProvider = ({ children }) =&gt; {<br>    const person = &quot;John&quot;;<br>    const data = [<br>        {<br>            id: 1,<br>            name: &quot;Harry&quot;,<br>            age: &quot;23&quot;,<br>        },<br>        {<br>            id: 2,<br>            name: &quot;Jerry&quot;,<br>            age: 43,<br>        },<br>    ];<br>    const clickFunction = () =&gt; {<br>        console.log(&quot;clicked!!&quot;);<br>    };<br>    return &lt;DataContext.Provider value={{ person, data, clickFunction }}&gt;{children}&lt;/DataContext.Provider&gt;;<br>};<br>export default ContextProvider;</pre><p>Let’s break the code so that it is easy to understand what is going on.</p><pre>import React, { createContext } from &quot;react&quot;;<br>export const DataContext = createContext(null);</pre><p>We created a context using <strong>createContext </strong>and we exported it so that it is accessible to other components.</p><pre>const ContextProvider = ({ children }) =&gt; {<br>    const person = &quot;John&quot;;<br>    const data = [<br>        {<br>            id: 1,<br>            name: &quot;Harry&quot;,<br>            age: &quot;23&quot;,<br>        },<br>        {<br>            id: 2,<br>            name: &quot;Jerry&quot;,<br>            age: 43,<br>        },<br>    ];<br>    const clickFunction = () =&gt; {<br>        alert(&#39;I am clicked!!&#39;);<br>    };<br>    return (<br>        &lt;DataContext.Provider<br>            value={{<br>                person,<br>                data,<br>                clickFunction,<br>            }}<br>        &gt;<br>            {children}<br>        &lt;/DataContext.Provider&gt;<br>    );<br>};<br>export default ContextProvider;</pre><p>We defined what we want to be globally accessible through that context and then through the provider, we provided those values. We want <strong>person</strong>, <strong>data</strong>, and <strong>clickFunction()</strong> to be accessed by any component throughout our app. The provider is the <strong>wrapper component</strong> and any children(components) inside that wrapper will have access to the values we provide after we export it.</p><blockquote><em>Note: We can pass any type of data. In the example above we passed string, object, and function to value prop.</em></blockquote><p>We will create a custom hook to consume/use that context.</p><p><strong>useAuth.js</strong></p><pre>import { useContext } from &#39;react&#39;;<br>import { AuthContext } from &#39;./ContextProvider&#39;;<br><br>const useAuth = () =&gt; useContext(AuthContext);<br><br>export default useAuth;</pre><p>Let’s see how we can implement it. Are you ready??</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLCSFRXKeV9rcBRLb8L%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLCSFRXKeV9rcBRLb8L%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FLCSFRXKeV9rcBRLb8L%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fcf14c62ad19a993a80b1a70a6fbbf3/href">https://medium.com/media/2fcf14c62ad19a993a80b1a70a6fbbf3/href</a></iframe><p>Create a file <strong>ComponentC.js</strong></p><p><strong>ComponentC.js</strong></p><pre>import React from &quot;react&quot;;<br>import useAuth from &quot;./useAuth&quot;;<br>const ComponentC = () =&gt; {<br>    const { person, data, clickFunction } = useAuth();<br>    return (<br>        &lt;&gt;<br>            &lt;h4&gt;Hello I am component C with name {person} and other data like &lt;/h4&gt;<br>            &lt;button onClick={clickFunction}&gt;Click Me&lt;/button&gt;<br>            {data.map((item) =&gt; {<br>                const { id, name, age } = item;<br>                return (<br>                    &lt;ul key={id}&gt;<br>                        &lt;li&gt;ID: {id}&lt;/li&gt;<br>                        &lt;li&gt;Name: {name}&lt;/li&gt;<br>                        &lt;li&gt;Age: {age}&lt;/li&gt;<br>                    &lt;/ul&gt;<br>                );<br>            })}<br>        &lt;/&gt;<br>    );<br>};<br>export default ComponentC;</pre><p>We imported the hook we created earlier and destructured the data.</p><pre>const { person, data, clickFunction } = useAuth();</pre><p>Remember we have passed them as objects inside the value props.</p><pre>&lt;DataContext.Provider<br>            value={{<br>                person,<br>                data,<br>                clickFunction,<br>            }}<br>        &gt;<br>            {children}<br>        &lt;/DataContext.Provider&gt;</pre><p>We are retrieving the same data to use in our Component.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZbTGPGnG8mbs9DCY3ZjvA.gif" /></figure><p>So did you learn something new?? Please feel free to modify and have some fun. Happy learning and see you around !!!</p><blockquote><a href="https://codesandbox.io/s/stoic-thunder-hxxmyo?file=/src/App.js">https://codesandbox.io/s/stoic-thunder-hxxmyo?file=/src/App.js</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5edaeb8ff1a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>