<?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 Anshul Tilondiya on Medium]]></title>
        <description><![CDATA[Stories by Anshul Tilondiya on Medium]]></description>
        <link>https://medium.com/@anshultilondiya?source=rss-6fac768f0a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9CMK8xzSbsGdBnv7Rp-nKA.png</url>
            <title>Stories by Anshul Tilondiya on Medium</title>
            <link>https://medium.com/@anshultilondiya?source=rss-6fac768f0a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:37:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anshultilondiya/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[What is Context API ? Implementation and use cases]]></title>
            <link>https://medium.com/acciojob/what-is-context-api-implementation-and-use-cases-faf84ff6e88c?source=rss-6fac768f0a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf84ff6e88c</guid>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[global-state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anshul Tilondiya]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 21:34:39 GMT</pubDate>
            <atom:updated>2023-04-25T06:48:47.229Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Context API ? Implementation and use cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2am_g7SyLHw5gvcIE6ZjFw.png" /></figure><p><strong>What is context API?</strong></p><p>Context API is a tool that allows the sharing of data and state throughout a React component hierarchy. It was introduced in React 16.3 as an alternative to the traditional method of passing down props through multiple layers of components. This new approach simplifies the code by providing a centralized location to store data, making it easier to access and update.</p><p>This concept holds the foundation of many global state management libraries. The most popular global state management library - <strong>Redux, uses context API under the hood to pass data across multiple levels of the component hierarchy.</strong></p><p><strong>Why do we need it?</strong></p><p>In complex React applications, it can be difficult to manage state and data flow. Passing data down through multiple layers of components can become cumbersome, leading to issues such as prop drilling and the inability to manage the state efficiently. Context API solves these problems by providing a centralized location to store data, making it easier to access and update.</p><p><strong>Let’s begin to understand how to implement it.</strong></p><p>To implement Context API, we first create a context object using the createContext() function. This context object can be accessed by any component within its hierarchy. The context provider is then created using the Provider component, which is used to wrap the components that require access to the context. The data that needs to be shared is passed down to the provider using the value prop. Finally, we can access the data in any component within the provider’s hierarchy using the useContext() hook.</p><p>Here’s an example:</p><p>We will start with creating the project using</p><pre>yarn create react-app context-api-example <br><br>// or <br><br>npx create-react-app context-api-example</pre><p>Then we will create a context file to make our context.</p><pre>import React, { createContext} from &#39;react&#39;;<br><br>export const AppContext = createContext(null);<br><br>const AppContextProvider = ({ children }) =&gt; {<br><br>  return (<br>    &lt;AppContext.Provider value={{}}&gt;<br>      {children}<br>    &lt;/AppContext.Provider&gt;<br>  );<br>};<br><br>export default AppContextProvider;</pre><p>Here, we created context using the createContext Hook and set the default value to null; this default value is the fallback value. Then we will create a provider component that will help us to provide the context store to our application. React uses provider pattern in Context API to share data across the tree descendant nodes. Therefore we have to return the provider (that we got from the context) from the “AppContextProvider” component. Whatever we put inside the value prop of this provider, it will be accessible throughout the application.</p><p>Now we will create our task list and some more functions that we will need for creating tasks and marking the tasks done or not done.</p><pre>import { nanoid } from &#39;nanoid&#39;;<br>import React, { createContext, useState } from &#39;react&#39;;<br><br>export const AppContext = createContext(null);<br><br>const AppContextProvider = ({ children }) =&gt; {<br>  const [taskList, setTaskList] = useState([]);<br><br>  const addTask = (task) =&gt; {<br>    const taskObj = {<br>      id: nanoid(),<br>      text: task,<br>      done: false,<br>    };<br>    setTaskList([taskObj, ...taskList]);<br>  };<br><br>  const markAsDone = (id, val) =&gt; {<br>    const taskIndex = taskList.findIndex((elem) =&gt; elem.id === id);<br>    const temp = [...taskList];<br>    temp[taskIndex].done = val === &quot;false&quot; ? true : false;<br>    setTaskList([...temp]);<br>  };<br><br>  return (<br>    &lt;AppContext.Provider value={{ taskList, addTask, markAsDone }}&gt;<br>      {children}<br>    &lt;/AppContext.Provider&gt;<br>  );<br>};<br><br>export default AppContextProvider;</pre><p>Here I have created functions for creating tasks and marking task completion. Now we will implement a taskList component</p><pre>import React, { useContext, useEffect, useState } from &#39;react&#39;;<br>import { AppContext } from &#39;../context/context&#39;;<br><br>const TaskList = () =&gt; {<br>  const { taskList, addTask, markAsDone } = useContext(AppContext);<br><br>  const [taskVal, setTaskVal] = useState(&#39;&#39;);<br><br>  const keyPressFun = (e) =&gt; {<br>    const keycode = e.which == 13;<br>    console.log(&#39;keycode&#39;, keycode);<br>  };<br><br>  return (<br>    &lt;div className=&#39;task-list&#39;&gt;<br>      &lt;div className=&#39;input-task&#39;&gt;<br>        &lt;input<br>          value={taskVal}<br>          onChange={(e) =&gt; setTaskVal(e.target.value)}<br>          placeholder=&#39;Add Task...&#39;<br>          onKeyPress={(e) =&gt; keyPressFun(e)}<br>        /&gt;<br>        &lt;button onClick={() =&gt; addTask(taskVal)}&gt;Add Task&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;ul&gt;<br>        {taskList.map((el) =&gt; (<br>          &lt;li key={el.id}&gt;<br>            &lt;input<br>              type=&#39;checkbox&#39;<br>              value={el.done}<br>              onChange={(event) =&gt; markAsDone(el.id, event.target.value)}<br>            /&gt;<br>            {el.text}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default TaskList;</pre><p>Here we have created an input box and list. For using the states or functions that we have created in context, we have to use the “useContext” hook.</p><pre>const { taskList, addTask, markAsDone } = useContext(AppContext);</pre><p>This is how we use the “useContext” hook and provides the context from which we want to extract the states or functions.</p><p>And finally, we will have our application ready.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-context-api-04gphr%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-context-api-04gphr%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F04gphr%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8331310f941cb5544a0418fb5fb7ea0/href">https://medium.com/media/b8331310f941cb5544a0418fb5fb7ea0/href</a></iframe><p>In this example, we create an AppContext using createContext(). We then create a provider for the context using the “AppContext.Provider” component. The user types in the input box and triggers the addTask function present in the context, and the task is added to the taskList, which is also present in the context. React observes the state change and re-renders the list.</p><p><strong>What are the use cases?</strong></p><p>Context API can be used in a variety of situations, such as:</p><ol><li>Theme management: Context API can be used to manage the application’s theme. The theme data can be stored in the context and accessed by any component within the theme provider’s hierarchy.</li><li>User authentication: Context API can be used to manage user authentication state. The authentication data can be stored in the context and accessed by any component within the authentication provider’s hierarchy.</li><li>Multilingual support: Context API can be used to manage multiple languages in an application. The language data can be stored in the context and accessed by any component within the language provider’s hierarchy.</li></ol><p>In conclusion, Context API simplifies data sharing and state management in complex React applications. It provides a centralized location to store data and makes it easier to access and update. By using Context API, developers can write more efficient and maintainable code.</p><p>If you want to learn more about coding concepts in details, be sure to check out our <a href="https://bit.ly/acciojobmedium">Full Stack Web Development Course</a>. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf84ff6e88c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/acciojob/what-is-context-api-implementation-and-use-cases-faf84ff6e88c">What is Context API ? Implementation and use cases</a> was originally published in <a href="https://medium.com/acciojob">AccioJob</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Protected / Private Routes using React Router v6]]></title>
            <link>https://medium.com/acciojob/handling-protected-private-routes-using-react-router-v6-772f0f2283f0?source=rss-6fac768f0a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/772f0f2283f0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nested-routes]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[protected-routes]]></category>
            <dc:creator><![CDATA[Anshul Tilondiya]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 05:12:17 GMT</pubDate>
            <atom:updated>2023-04-13T06:03:14.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vZUbv1itft60YwVULkHpQ.jpeg" /><figcaption>Handling Protected / Private Routes using React Router v6</figcaption></figure><p>Handling protected/private routes in a React application is a common requirement. In many cases, we want to restrict access to certain routes and only allow authenticated users to view them. In this article, we will explore how to handle private routes using react-router v6.</p><p>We will begin with creating a React Application; you can either use npm or yarn.</p><pre>npx create-reacte-app protected-routes<br>npm install react-router-dom</pre><p>or</p><pre>yarn create react-app protected-routes<br>yarn add react-router-dom</pre><p>Next, we will create a basic application with unprotected routers,</p><pre>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;<br>import { Routes, Route, Link } from &#39;react-router-dom&#39;;<br>import Home from &#39;./pages/home&#39;;<br>import Cart from &#39;./pages/cart&#39;;<br>import Profile from &#39;./pages/profile&#39;;<br>import Login from &#39;./pages/login&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function App() {<br>  const [username, setUsername] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br>  const [authenticated, setAuthenticated] = useState(false);<br><br>  return (<br>    &lt;div className=&#39;App&#39;&gt;<br>      &lt;nav className=&#39;nav&#39;&gt;<br>        &lt;Link to={&#39;/&#39;}&gt;Home&lt;/Link&gt;<br>        &lt;Link to={&#39;/cart&#39;}&gt;Cart&lt;/Link&gt;<br>        &lt;Link to={&#39;/profile&#39;}&gt;Profile&lt;/Link&gt;<br>        &lt;Link to={&#39;/login&#39;}&gt;Login&lt;/Link&gt;<br>      &lt;/nav&gt;<br>      &lt;Routes&gt;<br>        &lt;Route<br>          path=&#39;/&#39;<br>          element={&lt;Home /&gt;}<br>        /&gt;<br>        &lt;Route<br>          path=&#39;/cart&#39;<br>          element={&lt;Cart /&gt;}<br>        /&gt;<br>        &lt;Route<br>          path=&#39;/profile&#39;<br>          element={&lt;Profile /&gt;}<br>        /&gt;<br>        &lt;Route<br>          path=&#39;/login&#39;<br>          element={<br>            &lt;Login<br>              username={username}<br>              setUsername={setUsername}<br>              password={password}<br>              setPassword={setPassword}<br>              loginFun={() =&gt; setAuthenticated(true)}<br>            /&gt;<br>          }<br>        /&gt;<br>      &lt;/Routes&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Here, I have created a simple application, which has 4 routes; home, cart, profile, and login. These pages are nothing more than a simple component returning a heading show what pages they are.</p><pre>import React from &quot;react&quot;;<br><br>const Home = () =&gt; {<br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;This is Home Page&lt;/h1&gt;<br>        &lt;/div&gt;<br>    )<br>}<br><br>export default Home;</pre><p>So, If you wanna route to these pages, you will be free to move since there is no protection for any route</p><figure><img alt="Media File showing that all the routes are accessible, have no protection" src="https://cdn-images-1.medium.com/max/1024/1*EGMZbQUspv9W78hFiZIsQA.gif" /></figure><p>Now we will begin with our traditional approach of creating protected routes. We will create a component in which we will pass if the user is authenticated and it will return us a route accordingly.</p><pre>// privateRoute.jsx<br><br>import React from &#39;react&#39;;<br>import { Route } from &#39;react-router-dom&#39;;<br><br>const PrivateRoute = ({ auth, path, element }) =&gt; {<br>  return auth ? (<br>    &lt;Route<br>      path={path}<br>      element={element}<br>    /&gt;<br>  ) : null;<br>};<br><br>export default PrivateRoute;</pre><pre>// App.jsx<br><br>&lt;Route<br>   path=&#39;/&#39;<br>   element={&lt;Home /&gt;}<br> /&gt;<br>&lt;PrivateRoute<br>  auth={authenticated}<br>  path={&#39;/cart&#39;}<br>  element={&lt;Cart /&gt;}<br>/&gt;<br>&lt;Route<br>  path=&#39;/profile&#39;<br>  element={&lt;Profile /&gt;}<br>/&gt;</pre><p>But in doing so, you will get an error. This error occurs because, in v6 of react-router-dom, all the component that are children of &lt;Routes&gt; component has to be &lt;Route&gt;. Hence we will not be allowed to place any custom private route directly, even if it just returns a &lt;Route&gt; component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IU1cyMyphzjN3NVe1PRl1A.png" /></figure><p>Therefore we have to find out another way to implement private routes. This is where <strong>&lt;Outlet/&gt;</strong> comes into play. According to the <a href="https://reactrouter.com/en/main/components/outlet">official docs</a> -</p><p><em>“An </em><em>&lt;Outlet&gt; should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.”</em></p><p>In simple words Outlet, allows us to make complicated nested UI efficiently, i.e instead of writing complex route patterns like</p><pre>&lt;Route path=&quot;/dashboad/messages/:id&quot; element={...}/&gt;</pre><p>You can nest them easily</p><pre>&lt;Route path=&quot;/dashboard&quot; element={...}&gt;<br>  &lt;Route path=&quot;messages&quot; element={...}&gt;<br>    &lt;Route path=&quot;:id&quot; element={...}/&gt;<br>  &lt;/Route&gt;<br>&lt;/Route&gt;</pre><p>By nesting your routes this way you are able to render 3 different components i.e “/dashboard” will renderent a Dashboard component and when user moves to “/dashboard/message” another Messages component is rendered again if user goes to “/dashboard/messages/:id” then a different component could be rendered.</p><p>You can also visit the code snippet provided by react-router-dom’s offical docs <a href="https://reactrouter.com/en/main/components/outlet">here</a>.</p><p>So, having understood that we will move back to our main topic private routes.</p><p>Here we will resolve our error using &lt;Outlet&gt;.</p><pre>// App.jsx<br>.....<br>.....<br>&lt;Routes&gt;<br>  {/* Here we have nested our routes inside another route */}<br>  &lt;Route<br>    path=&#39;/&#39;<br>    element={&lt;Authenticated auth={authenticated} /&gt;}<br>    &gt;<br>      &lt;Route<br>         path=&#39;/&#39;<br>         element={&lt;Home /&gt;}<br>       /&gt;<br>       &lt;Route<br>         path=&#39;/cart&#39;<br>         element={&lt;Cart /&gt;}<br>       /&gt;<br>       &lt;Route<br>         path=&#39;/profile&#39;<br>         element={&lt;Profile /&gt;}<br>        /&gt;<br>    &lt;/Route&gt;<br>        ....<br>&lt;/Routes&gt;<br>.....<br>.....</pre><pre>// authenticate.jsx<br><br>import React from &#39;react&#39;;<br>import { Navigate, Outlet } from &#39;react-router-dom&#39;;<br><br>const Authenticated = ({ auth }) =&gt; {<br>  return auth ? &lt;Outlet /&gt; : &lt;Navigate to={&#39;/login&#39;} /&gt;;<br>};<br><br>export default Authenticated;</pre><p>This Authenticated Component, checks if the user is authenticated using the auth prop and renders the &lt;Outlet/&gt; component; if authenticated, it matches the path and renders the requested component, and if the user is not authenticated user is redirected to the login page with the help of &lt;Navigate/&gt; component which is a replacement of old &lt;Redirect/&gt; component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_UnI5G_cmAE3cMBXXN35A.gif" /></figure><h3>Conclusion</h3><p>In this article, we explored how to handle private routes using react-router v6. We learned that react-router-dom v6 does not allow the Routes component to have children other than Route. Hence we introduced &lt;Outlet/&gt; to solve the problem of private routes, and we created an Authenticated component to restrict access to certain routes and used it to protect serval routes. We also learned how to handle redirects if the user is not authenticated. With this knowledge, you should be able to handle private routes in your React applications with ease.</p><p>If you want to learn more about coding concepts in detail, be sure to check out our <a href="https://bit.ly/acciojobmedium">Full Stack Web Development Course</a>. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772f0f2283f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/acciojob/handling-protected-private-routes-using-react-router-v6-772f0f2283f0">Handling Protected / Private Routes using React Router v6</a> was originally published in <a href="https://medium.com/acciojob">AccioJob</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React Portal]]></title>
            <link>https://medium.com/acciojob/react-portal-a-guide-to-rendering-content-outside-of-components-dfeb9b913b95?source=rss-6fac768f0a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfeb9b913b95</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[modal]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-portal]]></category>
            <dc:creator><![CDATA[Anshul Tilondiya]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 18:42:18 GMT</pubDate>
            <atom:updated>2023-04-13T06:11:22.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYFOiBlSHsfsDoq8EZXx6w.png" /></figure><p>React is a popular JavaScript library for building user interfaces. One of its key features is the ability to create reusable components that can be used throughout an application. However, there may be times when you need to render content outside of a component, such as modals, popovers, or tooltips. That’s where React Portals come in. In this article, we’ll explore React Portals, why you might want to use them, and how to implement them in your React application.</p><h3><strong>What is React Portal?</strong></h3><p>React Portals is another helpful technique provided by the <strong>react-dom </strong>library. Using this technique, you can render content outside of a component’s parent DOM hierarchy. In other words, you can render content to an element that exists outside of the component tree. This is useful when you need to display content that is not part of the main layout of your application.</p><p>Some common use cases for React Portals are modals, popovers, tooltips, etc. These attention-seeking components are usually displayed on top of all other content and are not part of the main page layout. With React Portals, you can render these components to an element outside of the main application container, ensuring that it appears on top of all other content and have access to all the states and data of the parent.</p><h3><strong>Why Use React Portals?</strong></h3><p>You might want to use React Portals in your application for several reasons. Here are a few:</p><ol><li>Modals: As mentioned above, modals are a common use case for React Portals. By rendering the modal content outside of the main component hierarchy, you can ensure that it appears on top of all other content.</li><li>Performance: In some cases, rendering content directly to the DOM can be faster than rendering it through React components. React Portals allow you to take advantage of this by rendering certain elements outside of the main component hierarchy.</li><li>Separation of Concerns: By rendering content outside of a component’s parent hierarchy, you can keep your application’s code organized and easier to manage.</li></ol><h3><strong>How to Implement React Portals?</strong></h3><p>Implementing React Portals is fairly straightforward. You have to write a very small amount of code. It begins with a very simple step;</p><ul><li><strong>Create a new container element outside the root div<br></strong>First, you’ll need to create a new element that will serve as the container for your portal content. This element should be added next to the root div in your <strong>index.html</strong> file.</li></ul><pre>&lt;body&gt;<br>  &lt;div id=&quot;root&quot;&gt;&lt;/div&gt; // traditional root element provided by react itself<br>  &lt;div id=&quot;portal&quot;&gt;&lt;/div&gt; // A div created by us outsite root<br>&lt;/body&gt;</pre><ul><li><strong>Render the portal content.<br></strong>Next, you’ll need to render the portal content to the new container element using ReactDOM.createPortal(). This function takes two arguments: the content to be rendered, and the target container element.</li></ul><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br><br>const PortalCreator = ({ children }) =&gt; {<br>  const mount = document.getElementById(&#39;portal&#39;);<br>  return ReactDOM.createPortal(children, mount);<br>};<br><br>export default PortalCreator;</pre><p>Now this HOC can be used to render any component to the div we create outside the root div.</p><ul><li><strong>Using the Portal Component <br></strong>For using the PortalCreator component, import it in any file you wish to use it and then pass the desired component to this portal component as children.</li></ul><pre>&lt;PortalCreator&gt;<br>  &lt;h1&gt;This will be rendered inside the portal div &lt;h1&gt;<br>&lt;/PortalCreator&gt;</pre><p>Now this “&lt;h1&gt;” will be rendered inside the div having “#portal” id, which exists outside of the main component hierarchy.</p><h3><strong>Conclusion</strong></h3><p>React Portals are a powerful tool for rendering content outside of a component’s parent DOM hierarchy. They can be used for modals, popovers, tooltips, and more. By using React Portals, you can improve your application’s performance and keep your code organized.</p><p>An actual tutorial with a demo will be available soon …..</p><p>Till then, If you want to learn more about coding concepts in details, be sure to check out our <a href="https://bit.ly/acciojobmedium">Full Stack Web Development course</a>. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfeb9b913b95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/acciojob/react-portal-a-guide-to-rendering-content-outside-of-components-dfeb9b913b95">Understanding React Portal</a> was originally published in <a href="https://medium.com/acciojob">AccioJob</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Mobx with React Functional Components]]></title>
            <link>https://medium.com/acciojob/using-mobx-with-react-functional-components-7f486ae21c5b?source=rss-6fac768f0a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f486ae21c5b</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobx-react]]></category>
            <category><![CDATA[todo]]></category>
            <category><![CDATA[mobx]]></category>
            <dc:creator><![CDATA[Anshul Tilondiya]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 18:47:32 GMT</pubDate>
            <atom:updated>2023-04-13T06:50:19.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeTss0B00T6NuEPhhWILSA.png" /><figcaption>Using Mobx with React Functional Components</figcaption></figure><p>In this tutorial, we will learn how to use MobX with React Functional Components. MobX being a very useful state management library reduces the code that needs to be written for global state management. Mobx is easy to use and quick to learn. We will implement some concepts of MobX in a todo application.</p><p>Github link: <a href="https://github.com/Anshultilondiya/react-mobx-medium">https://github.com/Anshultilondiya/react-mobx-medium</a></p><p>Let’s start with creating react application</p><pre>npx create-react-app todo<br>cd todo</pre><p>Now we will install some other dependencies to our todo application. (I’ll be using <a href="https://yarnpkg.com/">yarn</a> as a package management tool, feel free to use your favorite package manager)</p><pre>yarn add mobx mobx-react nanoid material-ui/core</pre><p>Nano ID is a lightweight secure string ID generating library, we will use nanoid for generating unique IDs for our todos.</p><p>Let’s now start our development server using yarn</p><pre>yarn start</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-mobx-todo-kycezi%3Fautoresize%3D1%26codemirror%3D1%26fontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-mobx-todo-kycezi%3Fautoresize%3D1%26codemirror%3D1%26fontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fkycezi%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9d6c961170d235328964207ac81e368/href">https://medium.com/media/a9d6c961170d235328964207ac81e368/href</a></iframe><p>Now, we will begin our code by creating a global data store at <strong><em>src/Store/store.js</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0807adcf0ae830cca0bbd80cf18bb466/href">https://medium.com/media/0807adcf0ae830cca0bbd80cf18bb466/href</a></iframe><blockquote>Here, the variable <strong>todoList </strong>contains all our todo and our store have 3 functions that perform certain operations :<br><strong><em>addTodo</em></strong> function is responsible for adding a todo to our todoList<br><strong><em>complete</em></strong> function marks a todo as done {done : true}<br><strong><em>incomplete</em></strong> function marks a todo as not done {done : false}</blockquote><p>Further, we move towards providing the data of this store to our app using a context provider. Context Provider is used for providing data to all the child components wrapped inside it. You can read about React Context API <a href="https://reactjs.org/docs/context.html">here</a>.</p><p><strong><em>src/ContextProvider/todoContext.js</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/268090ac950404bb24ef2e8e79dcdb80/href">https://medium.com/media/268090ac950404bb24ef2e8e79dcdb80/href</a></iframe><p>Firstly, we will create a context using <strong><em>createContext()</em></strong> and set the default value of context as null. Then we will create a Provider component that will pass down the data to all the children components. <strong><em>useLocalObservable()</em> is used to make create a new Observable object</strong> and keeps it around in the component for the entire life-cycle of the component. useTodoStore function is used to return the current value of the context created using <strong><em>createContext()</em></strong>. This function will be used further for getting the current values of the store.</p><p>Now we will wrap our App component with our recently created Context. Let’s move to index.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7cf90e9160c53a996858b407abe7022/href">https://medium.com/media/a7cf90e9160c53a996858b407abe7022/href</a></iframe><p>Here, we have wrapped our App.js component with <strong><em>&lt;TodoProvider&gt;</em></strong> so that our whole app will be able to access the store.</p><p>Next, we will move towards creating reactive components that will be able to mutate the store data. First, we will add an input field to our app in App.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71632547fac524789b56bbd5274834a0/href">https://medium.com/media/71632547fac524789b56bbd5274834a0/href</a></iframe><p>As mentioned earlier we will use the useTodoStore() function that was defined in the <em>todoContext.js </em>for getting the current context value. Here, we called the function and stored the current Context value in a variable and further all the accessing is done by that variable. <strong><em>&lt;Observer&gt; </em></strong>renders a reactive component that gets re-render whenever needed.</p><p>Now, we will create a list component {<strong><em>src/Components/listTodo.js</em></strong>}that will render all the todos in a classified manner <br>Remaining: Contains all the incomplete tasks.<br>Done: Contains all the completed tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67648e051f36e5d7aa774fb1f841c611/href">https://medium.com/media/67648e051f36e5d7aa774fb1f841c611/href</a></iframe><p>Here, we have created a component {<strong><em>src/Components/completedTodo.js</em></strong>} that contains all the completed tasks only and has a undo button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e16b384d4170a93904eaa66b8e29b3a/href">https://medium.com/media/7e16b384d4170a93904eaa66b8e29b3a/href</a></iframe><p>Here, we have created a component {<strong><em>src/Components/incompleteTodo.js</em></strong>} that contains all the incompleted tasks only and has a done button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba93b21c3e79ae7eaf1a7fd8cf55a3a1/href">https://medium.com/media/ba93b21c3e79ae7eaf1a7fd8cf55a3a1/href</a></iframe><p>Further, we have added all the components in our App component with some grid adjustment for design purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/305b7020ffb9f7dae216b5dc2916bfa4/href">https://medium.com/media/305b7020ffb9f7dae216b5dc2916bfa4/href</a></iframe><p>Hope this tutorial helped you in implementing MobX …</p><p>To learn more about coding concepts, be sure to check out our <a href="https://bit.ly/acciojobmedium">Full Stack Web Development Course</a>. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f486ae21c5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/acciojob/using-mobx-with-react-functional-components-7f486ae21c5b">Using Mobx with React Functional Components</a> was originally published in <a href="https://medium.com/acciojob">AccioJob</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>