<?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 Tarak on Medium]]></title>
        <description><![CDATA[Stories by Tarak on Medium]]></description>
        <link>https://medium.com/@subalerts?source=rss-1b01c46cc3b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Tarak on Medium</title>
            <link>https://medium.com/@subalerts?source=rss-1b01c46cc3b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 08:14:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@subalerts/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[WYSIWYG Editor for React: Jodit Editor (with Vite and TypeScript)]]></title>
            <link>https://medium.com/@subalerts/wysiwyg-editor-for-react-jodit-editor-with-vite-and-typescript-9e40c28fba8b?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e40c28fba8b</guid>
            <category><![CDATA[wysiwyg-editor]]></category>
            <category><![CDATA[jodit-editor]]></category>
            <category><![CDATA[text-formatting]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[wysiwyg]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 14:43:39 GMT</pubDate>
            <atom:updated>2024-09-27T14:43:39.345Z</atom:updated>
            <content:encoded><![CDATA[<p>It has been a long time since I had written any article :)</p><p>In my recent project, I had to integrate a free WYSIWYG Editor for my application and after analysing multiple libraries, settled with Jodit Editor.</p><p>Jodit Editor is a fast and lightweight WYSIWYG (What You See Is What You Get) editor, offering a rich text editing experience. It’s an ideal choice for React applications, thanks to its seamless integration, customization options, and wide feature set.</p><p>This post will show how to set up and use Jodit Editor in a React project. We’ll use <strong>Vite</strong> as the build tool, and <strong>TypeScript</strong> to ensure strong typing and scalable development.</p><h3><strong>Steps to Setup and Use Jodit Editor with Vite and TypeScript</strong></h3><ol><li><strong>Create a React App with Vite and TypeScript</strong></li></ol><pre>npm create vite@latest my-jodit-editor-app -- --template react-ts<br>cd my-jodit-editor-app<br>npm install</pre><p>This will set up a new Vite project with React and TypeScript support.</p><p>2. <strong>Install Jodit Editor and Jodit-React</strong></p><p>Install the necessary packages for Jodit and Jodit-React:</p><pre>npm install jodit jodit-react</pre><p>3. <strong>Setting up the Editor Component</strong></p><p>Next, create a component called EditorComponent.tsx. This component will render the Jodit Editor and handle its content.</p><pre>// src/components/EditorComponent.tsx<br>import React, { useRef, useState } from &#39;react&#39;;<br>import JoditEditor from &#39;jodit-react&#39;;<br><br>const EditorComponent: React.FC = () =&gt; {<br>    const editor = useRef(null);<br>    const [content, setContent] = useState&lt;string&gt;(&#39;&#39;);<br><br>    const config = {<br>        readonly: false,<br>        height: 400,<br>        toolbarButtonSize: &#39;middle&#39;,<br>        buttons: [&#39;bold&#39;, &#39;italic&#39;, &#39;underline&#39;, &#39;link&#39;, &#39;unlink&#39;, &#39;source&#39;],<br>        uploader: {<br>            insertImageAsBase64URI: true,<br>        },<br>    };<br><br>    return (<br>        &lt;div&gt;<br>            &lt;JoditEditor<br>                ref={editor}<br>                value={content}<br>                config={config}<br>                tabIndex={1} // tabIndex of textarea<br>                onBlur={(newContent: string) =&gt; setContent(newContent)}<br>                onChange={(newContent: string) =&gt; {}}<br>            /&gt;<br>            &lt;div style={{ marginTop: &#39;20px&#39; }}&gt;<br>                &lt;h3&gt;Content:&lt;/h3&gt;<br>                &lt;pre&gt;{content}&lt;/pre&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default EditorComponent;</pre><p>In this file:</p><ul><li>We initialize content to store the text entered into the editor.</li><li>The onBlur handler updates the content state with the editor&#39;s content after the user is done editing.</li><li>We configure basic toolbar buttons like bold, italic, underline, and link.</li><li>Images are inserted as base64 strings using the uploader config.</li></ul><p>4. <strong>Integrate the Editor into Your App</strong></p><p>Now, import the EditorComponent into your main App.tsx file to display it.</p><pre>// src/App.tsx<br>import React from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import EditorComponent from &#39;./components/EditorComponent&#39;;<br><br>const App: React.FC = () =&gt; {<br>    return (<br>        &lt;div className=&quot;App&quot;&gt;<br>            &lt;h1&gt;Jodit Editor with React and TypeScript&lt;/h1&gt;<br>            &lt;EditorComponent /&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default App;</pre><p>This will add the Jodit Editor to the app and allow users to type text and view the content.</p><p>5. <strong>Run the Project</strong></p><p>To start the development server, use:</p><pre>npm run dev</pre><p>You can now open your browser and see the editor live at http://localhost:5173. The editor should allow you to format text, insert links, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKy7HSHjlG3Y33AXUHNBLw.png" /></figure><p>Here, I have copied some random text from w3 schools and as we can see, text has been copied with formatting.</p><p>We can preview using ‘eye’ icon</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ag666urMfxfKSNz7_TfHbw.png" /></figure><p>6. <strong>Handling Custom Paste Events for Image Conversion</strong></p><p>Jodit Editor is highly customizable. For example, if you want to handle image paste events (such as converting images to base64 before inserting them), you can modify the paste event as shown below:</p><pre>const handlePaste = (event: ClipboardEvent) =&gt; {<br>    const clipboardData = event.clipboardData;<br>    const items = clipboardData?.items;<br><br>    if (items) {<br>        for (let i = 0; i &lt; items.length; i++) {<br>            if (items[i].type.indexOf(&#39;image&#39;) === 0) {<br>                const file = items[i].getAsFile();<br>                const reader = new FileReader();<br><br>                reader.onload = (e) =&gt; {<br>                    const base64Image = e.target?.result as string;<br>                    setContent((prevContent) =&gt; prevContent + `&lt;img src=&quot;${base64Image}&quot; alt=&quot;Pasted Image&quot;/&gt;`);<br>                };<br><br>                if (file) {<br>                    reader.readAsDataURL(file);<br>                }<br>            }<br>        }<br>    }<br>};<br><br>// Add the paste handler to the JoditEditor configuration<br>const config = {<br>    events: {<br>        beforePaste: handlePaste,<br>    },<br>};</pre><p>This will convert any pasted image into a base64 string and insert it into the editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69o5yhvUtvOUYQZILWo1UQ.png" /></figure><p>Screenshot of paste table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJI9LuKt7O8iWZjokPykRA.png" /></figure><p>7. <strong>Customizing the Toolbar and Configuration</strong></p><p>You can further customize the toolbar and behavior of Jodit Editor. Below is an example where we limit the toolbar to a few essential tools:</p><pre>const config = {<br>    readonly: false,<br>    toolbarButtonSize: &#39;middle&#39;,<br>    buttons: [&#39;bold&#39;, &#39;italic&#39;, &#39;underline&#39;, &#39;link&#39;, &#39;unlink&#39;, &#39;source&#39;],<br>    height: 400,<br>    uploader: {<br>        insertImageAsBase64URI: true, // Automatically convert images to base64<br>    },<br>    events: {<br>        afterInit: (editor: any) =&gt; console.log(&#39;Editor initialized&#39;),<br>    },<br>};</pre><p>This configuration restricts the toolbar buttons to bold, italic, underline, and linking options</p><h3>Final Thoughts</h3><p>Jodit Editor is a highly flexible WYSIWYG editor that integrates seamlessly into React projects. Using Vite with TypeScript adds even more efficiency and scalability to your project.</p><p>You can further explore <a href="https://xdsoft.net/jodit/docs/">Jodit’s API documentation</a> to enhance your project.</p><h3>GitHub Repository</h3><p>You can find the full code for this tutorial on GitHub:</p><p><a href="https://github.com/tarakeshs/my-jodit-editor-app"><strong>GitHub Repo Link</strong></a></p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e40c28fba8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding hooks in react js]]></title>
            <link>https://medium.com/@subalerts/understanding-hooks-in-react-js-9f1497111e7f?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f1497111e7f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[counter]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Sat, 16 May 2020 13:43:18 GMT</pubDate>
            <atom:updated>2020-05-16T13:43:18.450Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will try to understand hooks in react js by writing a simple counter example using hooks</p><p>According to official <a href="https://reactjs.org/docs/hooks-intro.html">react js documentation</a> a hook lets you to use state and other react features without writing a class. If we write a class based component and import UseHook and use it in code, we get an error saying hooks can be used only in a functional components. Meaning, hooks can help to hook state into a functional component.</p><p>Let us write a simple counter example using hooks.</p><p>Start by writing a functional component and three functions to increment, decrement and rest. Add buttons to increase, decrease and reset counter. Basic template looks as follows</p><pre>import React from &quot;react&quot;;</pre><pre>function App() {</pre><pre>const increment = () =&gt;{</pre><pre>}</pre><pre>const decrement = () =&gt;{</pre><pre>}</pre><pre>const reset = () =&gt;{</pre><pre>}</pre><pre>return (</pre><pre>&lt;div className=&quot;App&quot;&gt;</pre><pre>&lt;button className=&#39;inc&#39;&gt;Increment!&lt;/button&gt;</pre><pre>&lt;button className=&#39;dec&#39;&gt;Decrement!&lt;/button&gt;</pre><pre>&lt;button className=&#39;reset&#39;&gt;Reset&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><p>In order to use hooks, import ‘useState’ from ‘react’. Using the useState hook, add a state called count and a function to update counter value called ‘setCount’. Updated component would look as follows</p><pre>import React, <strong>{useState}</strong> from &quot;react&quot;;</pre><pre>function App() {<br><strong>const [count, setCount] = useState(0);</strong></pre><pre>const increment = () =&gt;{</pre><pre>}</pre><pre>const decrement = () =&gt;{</pre><pre>}</pre><pre>const reset = () =&gt;{</pre><pre>}</pre><pre>return (</pre><pre>&lt;div className=&quot;App&quot;&gt;</pre><pre>&lt;button className=&#39;inc&#39;&gt;Increment!&lt;/button&gt;</pre><pre>&lt;button className=&#39;dec&#39;&gt;Decrement!&lt;/button&gt;</pre><pre>&lt;button className=&#39;reset&#39;&gt;Reset&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><p>As we can see from above code, we initialize useState with a default value of 0 for the counter. Meaning, value of count is set to 0.</p><p>As discussed above, setCount can be used to set a new value to the count variable. In order to increment/decrement, and rest we can use setCount(count+1)/setCount(count-1) and setCount(0)</p><pre>import React, <strong>{useState}</strong> from &quot;react&quot;;</pre><pre>function App() {<br><strong>const [count, setCount] = useState(0);</strong></pre><pre>const increment = () =&gt;{<br>   <strong><em>setCount(count+1);</em></strong><br>}</pre><pre>const decrement = () =&gt;{<br>   <strong><em>setCount(count-1);</em></strong><br>}</pre><pre>const reset = () =&gt;{<br>   <strong><em>setCount(0);</em></strong><br>}</pre><pre>return (</pre><pre>&lt;div className=&quot;App&quot;&gt;</pre><pre>&lt;button className=&#39;inc&#39;&gt;Increment!&lt;/button&gt;</pre><pre>&lt;button className=&#39;dec&#39;&gt;Decrement!&lt;/button&gt;</pre><pre>&lt;button className=&#39;reset&#39;&gt;Reset&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><p>Next step is only to bind the onClick listener of buttons to corresponding functions and display the count value in return function (render)</p><p>Our final code will be as follows</p><pre>import React, <strong>{useState}</strong> from &quot;react&quot;;</pre><pre>function App() {<br><strong>const [count, setCount] = useState(0);</strong></pre><pre>const increment = () =&gt;{<br>   <strong><em>setCount(count+1);</em></strong><br>}</pre><pre>const decrement = () =&gt;{<br>   <strong><em>setCount(count-1);</em></strong><br>}</pre><pre>const reset = () =&gt;{<br>   <strong><em>setCount(0);</em></strong><br>}</pre><pre>return (</pre><pre>&lt;div className=&quot;App&quot;&gt;</pre><pre>&lt;button className=&#39;inc&#39; <strong><em>onClick={increment}</em></strong>&gt;Increment!&lt;/button&gt;</pre><pre>&lt;button className=&#39;dec&#39; <strong><em>onClick={decrement}</em></strong>&gt;Decrement!&lt;/button&gt;</pre><pre>&lt;button className=&#39;reset&#39; <strong><em>onClick={reset}</em></strong>&gt;Reset&lt;/button&gt;</pre><pre><strong><em>&lt;h1&gt;Current Count: {count}&lt;/h1&gt;</em></strong></pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><p>Output of code is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*fNK926qi-IdTi3ZirVpUqw.gif" /></figure><p>Working example of the same can be found in the following <a href="https://codesandbox.io/s/react-counter-with-hooks-ln4uc">sandbox</a></p><p>Happy Learning :)</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f1497111e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Throw error if API fails to load in specific time in javascript]]></title>
            <link>https://medium.com/@subalerts/throw-error-if-api-fails-to-load-in-specific-time-in-javascript-6d3bc33893c5?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d3bc33893c5</guid>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[time-out]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Thu, 05 Sep 2019 13:51:23 GMT</pubDate>
            <atom:updated>2019-09-05T13:51:23.933Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to discard API call if there is no response in specific time in javascript</h3><p>Recently I have been to an interview and the interviewer asked the following question</p><blockquote>“You made an API call that does huge computation and returns data. Write code that checks if your API returned data in 5 seconds. If data is not returned in 5 seconds, throw error onto the console.”</blockquote><p>Let us write code to do the same. In Java script we have setTimeout, a timer function that executes function after a certain amount of time(milliseconds). I have given a solution by keeping a flag. On getting response form API, we make the flag to true. In SetTimeout, we check after 5 seconds if the flag is true/false. If the flag is false, meaning we did not get response yet.</p><p>Code for the same is as follows:</p><pre>// Initialize flag<br>var flag = false;</pre><pre>fakeAPI().then(res=&gt;{</pre><pre>// In the API&#39;s response, set the flag to true<br>flag = true; <br>console.log(res)});</pre><pre>setTimeout(function(){<br>// In the timer function that gets executed after 5 seconds, check // the flag value. If we got the response already it would have been // set to true. Otherwise false</pre><pre>if(flag==false){</pre><pre>console.error(&quot;Did not get response in 5 seconds&quot;);</pre><pre>throw new Error(&quot;ERROR&quot;);</pre><pre>}</pre><pre>}, 5000);</pre><p>Executing the above code would result in the following at js console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Tya-yOxOXzdau-I_f_8JBA.png" /></figure><p>Working example of the same can be found in the following <a href="https://next.plnkr.co/edit/FH3WoRcdyr38UeFT">plunker</a></p><p>The above code works as it logs error message onto console. Though error message is displayed, we also see the response being logged after 10 seconds. Let us try to remove that as well. Simplest thing that can be done is wrapping our API call in a promise and return rejection if the api does not respond back with in 5 seconds. Take a look at my other article on <a href="https://medium.com/@subalerts/understanding-promise-and-promise-chain-in-javascript-e07e9c7e2b50">Promises</a> for more information.</p><p>Let us create a function that takes ajax request and timeout as parameters. Inside that we return a promise object.</p><pre>function apiWithTimeout(httpReq, milliseconds) {</pre><pre>return new Promise(function(resolve, reject) {<br>// Our code goes here</pre><pre>})</pre><pre>};</pre><p>Inside the promise, we can use setTimeout to check for the specified number of milliseconds and send send rejection. Since we do a rejection, though we get response after 10sec, it would not be captures as it has been rejected already. Otherwise we resolve the promise with the response from API.</p><pre>setTimeout(function() {</pre><pre>reject(new Error(&quot;Data fetch failed in &quot;+milliseconds+&quot; ms&quot;))</pre><pre>}, milliseconds)</pre><pre>httpReq.then(res=&gt;{resolve(res)}, err=&gt;{reject(err)})</pre><p>Combining all together, our function would be as follows:</p><pre>function apiWithTimeout(httpReq, milliseconds) {</pre><pre>return new Promise(function(resolve, reject) {</pre><pre>setTimeout(function() {</pre><pre>reject(new Error(&quot;Data fetch failed in &quot;+milliseconds+&quot; ms&quot;))</pre><pre>}, milliseconds)</pre><pre>httpReq.then(res=&gt;{resolve(res)}, err=&gt;{reject(err)})</pre><pre>})</pre><pre>};</pre><pre>apiWithTimeout(fakeAPI(), 5000).then(res=&gt;{console.log(res)}).catch(err=&gt;{console.log(err.message)});</pre><p>Output of the code will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*y1irXZOovEqGCBtm166GYg.png" /></figure><p>Working example of the same can be found in the following <a href="https://next.plnkr.co/edit/ufRF2Qax5IGBorsc?open=lib%2Fscript.js">plunker</a></p><p>Happy Learning :)</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d3bc33893c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Promise and Promise Chain in javascript]]></title>
            <link>https://medium.com/@subalerts/understanding-promise-and-promise-chain-in-javascript-e07e9c7e2b50?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07e9c7e2b50</guid>
            <category><![CDATA[promise-chain]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[js-promise]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 12:41:06 GMT</pubDate>
            <atom:updated>2019-07-08T12:57:48.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Promise and Promise Chain in Javascript</h3><p>In this article, we will discuss about promises in javascript and then look at ayanc/await and how promises can be simplified using using async/await.</p><p>In generic, if we search for definition of promise in google, we get the following definition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*nGmKEZNe9U0M51IQF4xr_A.png" /></figure><p>Promise in javascript also works the same way. Let us take a real world example and convert it to Javascript syntax.</p><p>Imagine yourself and your friend plan to go to a movie. A typical conversation can be like this</p><blockquote><em>Me: Hello &lt;friend&gt;, shall we got to movie?</em></blockquote><blockquote><em>Friend: Yes, Sure</em></blockquote><blockquote><em>Me: But I do not have Tickets</em></blockquote><blockquote><em>Friend: Sure, no problem, I will get it for us. It’s a promise</em></blockquote><blockquote><em>Now, if our friend could get tickets </em><strong><em>then </em></strong><em>both would go to movie. Else both would not go</em></blockquote><p>If we try to put the above scenario in syntactical way, friend’s promise can be written as follows</p><pre>var promiseToGetTickets = new Promise(function(resolve, reject){<br>     <br> if(friend_got_tickets){<br>            <br>  resolve(&#39;got the tickets&#39;)<br>    <br> }else{<br>              <br>  reject(&#39;no tickets&#39;)<br> <br>}</pre><pre>})</pre><p>Now, when our friend tries to resolve promise</p><pre>promiseToGetTickets.then(function(success){</pre><pre>// got the tickets<br> console.log(&#39;go to movie&#39;);<br>}, function(failure){<br> // no tickets<br> console.log(&#39;both don\&#39;t go to movie&#39;)<br>})</pre><p>Now, let us try to understand the above syntax</p><pre>new Promise(function(<strong>resolve, reject</strong>){})</pre><p>As we can see, a promise object gives us two states, resolve and reject. If the promise is <strong>fulfilled</strong>, we would need to <strong>resolve</strong> it, <strong>else reject</strong> the same. Until this point of time, till the promise is resolved or rejected, recipient doesn’t know the status of the promise and we call it as <strong>pending</strong> state.</p><p>The recipient of the promise would capture the result of it using <strong>.then() </strong>syntax, which has two call backs for success, or failure. If the promise is resolved, the callback would be passed to success otherwise it goes to failure block</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QZcGvpHD6D8CcsQqnoylQ.png" /></figure><p>A typical example of promise in real-world application is while making API calls, where we wait for certain response form our service to provide the data to be displayed on the UI. When the promise is being executed (state=pending), we display loading message and once it’s resolved (state=fulfilled) user’s data will be displayed on the screen. Otherwise (state=rejected) error message will be displayed on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*2JCeu0w10kimcekJM2X0PQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*FZD6PwKywbekvEMigKepxQ.gif" /><figcaption>Error and success callbacks examples.</figcaption></figure><p>Typical code for the above scenario can be written as follows:</p><pre>// fakeAPI here returns a promise<br>var <strong>userDetails = fakeAPI(1)</strong>;</pre><pre>var detailsDiv = document.getElementById(&#39;details&#39;);</pre><pre>detailsDiv.innerHTML = &#39;Loading User details...!!!&#39;;</pre><pre>userDetails.<strong>then</strong>(function(succcess){</pre><pre>var data = `Name : ${succcess.userName}, Phone: ${succcess.phone}`;</pre><pre>detailsDiv.innerHTML = data;</pre><pre>}, function(error){</pre><pre>detailsDiv.innerHTML = &#39;Error loading user details&#39;;</pre><pre>})</pre><p>Working example of the same can be found at the following <a href="https://next.plnkr.co/edit/fmBb6nfNOPfJmMJA?open=lib%2Fscript.js&amp;preview">plunker</a></p><h3><strong>Promise Chaining</strong></h3><p>Now let us improvise the above scenario. Imagine the situation where you get the user details by Id. From the user details, we take user’s location and from the location we need to find out temperature at that particular location and all of this has to be done asynchronously</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*FNqvdBttXv9ZSw6crEmZMQ.png" /></figure><p>If we try to write code for the specific scenario, code will be as follows</p><pre>getUserDetailsById(){<br> ...<br> ...<br> // after we get response<br> getLocationByCode(){<br>  ...<br>  ...<br>  // after we get location name<br>  getTemperatureByLocation(){<br>   ...<br>   ...<br>   //update temperature to UI<br>  }<br> }<br>}</pre><p>Here, we are trying to execute sequence of API calls where input of the next call depends on the response of the previous one. In the pseudo code above, doing these kind of asynchronous calls one after other would result in writing large number of functions one inside another like below</p><pre>function_1(){<br> ...<br> function_2(){<br>  ...<br>   ...<br>    ...<br>    function_n(){<br>     ....<br>    }<br> }<br>}</pre><p>The above code works, but there’s another way of doing this in a better way using Promise Chain mechanism.</p><p>In promise chaining, if you pass another promise as a callback to the parent promise, it will wait until the child promise gets resolved. Hence, we can pass the next promise to the .then() response of the previous one and this way promises can be chained.</p><p>If we write code for the same, it would be as follows</p><pre>var getUserById = function(id) {<br>   var promise = new Promise(function(resolve, reject){<br>      setTimeout(function() {<br>        console.log(&#39;User id: &#39;+id);<br>        resolve({&#39;name&#39;: &#39;tom&#39;, &#39;locationCode&#39;: &#39;AG&#39;});<br>      }, 2000);<br>   });<br>   return promise;<br>};<br> <br> <br>var getLocationByCode = function(userData) {<br>  document.getElementById(&#39;name&#39;).innerText = userData.name;<br>   var promise = new Promise(function(resolve, reject){<br>      setTimeout(function() {<br>        console.log(&#39;Location code: &#39;+userData.locationCode);<br>        resolve({&#39;location&#39;:&#39;Asgard&#39;});<br>      }, 2000);<br>   });<br>   return promise;<br>};<br> <br>var getTemperatureByLocation= function(location) {<br>  document.getElementById(&#39;location&#39;).innerText = location.location;<br>   var promise = new Promise(function(resolve, reject){<br>      setTimeout(function() {<br>        console.log(&#39;Location Name: &#39;+location.location);<br>        resolve({&#39;temperature&#39;: &#39;30&#39;});<br>      }, 3000);<br>   });<br>   return promise;<br>};</pre><pre>document.getElementById(&#39;loading&#39;).innerHTML = &quot;Loaging data..!!&quot;;</pre><pre><strong>getUserById(1).<br>then(getLocationByCode).<br>then(getTemperatureByLocation).<br>then</strong>(function(success){<br>  document.getElementById(&#39;temp&#39;).innerText = success.temperature+&#39;ᵒ C&#39;;<br>  document.getElementById(&#39;loading&#39;).innerHTML = &quot;Data Loaded!&quot;;<br>});</pre><p>The result of getUserById is passed to getLocationByCode. It’s result is passed to getTemperatureByLocation. It can be easily represented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mH5Wljv8CpHmvk8HmT7dmw.png" /></figure><p>Result of the above code looks as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*tbAW1QK_7tW3tDpQuNGpeg.gif" /></figure><p>Working example of the same can be found in the following <a href="https://next.plnkr.co/edit/kNuqFgeoG5HbA65Y?open=lib%2Fscript.js&amp;preview">plunker</a></p><p>Happy learning :)</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07e9c7e2b50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding high-order component in React js]]></title>
            <link>https://medium.com/@subalerts/understanding-high-order-component-in-react-js-b26bfe3a7d26?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b26bfe3a7d26</guid>
            <category><![CDATA[search-hoc]]></category>
            <category><![CDATA[react-hoc]]></category>
            <category><![CDATA[high-order-component]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[hoc]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Sat, 11 May 2019 13:15:30 GMT</pubDate>
            <atom:updated>2019-05-11T13:15:30.048Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we would try to understand what is a high-order component, called as HOC in react js and write an example to see how a HOC can be implemented.</p><p>According to official <a href="https://reactjs.org/docs/higher-order-components.html">reactjs </a>website, <strong>a higher-order component is a function that takes a component and returns a new component</strong>.</p><p>A typical syntax of HOC would be as follows:</p><pre>const HOC = (WrappedComponent) =&gt; {<br> return class UpdatedComponent extends React.Component{<br> // Logic to initialize props/functions that are required by HOC<br> render(){<br> return(<br> &lt;WrappedComponent {…this.props} <strong>{/* any new props that are added by HOC */}</strong>/&gt;<br> )<br> }<br> }<br>}</pre><p>A typical example of HOC would be to implement localStorage or sessionStorage to get/set the user information or checking for authentication or implementing protected routes that needs a specific role or permission or any common functionality that is required by other components. ‘connect ’ from react-redux and ‘withRouter’ from React router are some of the frequent HOC that we typically use in our applications.</p><p>Now, let us write a small high-order-component that would add a search bar on top of table and could perform search operation on a specific field/column that we would want.</p><p>For this, I would be creating four components, App.jsx that would contain the json data from which our tables will be generated, MyList.jsx that would be wrapped around our HOC, Table.jsx that would dynamically create the table based on our json and SearchListHOC that would add the search box above our table and update the data of the MyList component with the search result.</p><p>Let us start by creating our HOC. Our High-order-component should do the following:</p><ul><li>Add a search box above our Wrapped component and send the filtered data back to our wrapped component</li><li>Add a change listener so that a function will be called for keypress</li><li>Implement a function that would return the filtered data based on the input/search box value that should be passed back to the wrapped component</li></ul><p>According to this, our render block of the HOC can be written as</p><pre>render() {<br> return (<br> &lt;div&gt;<br> &lt;div&gt;<br> <strong>&lt;input onChange={this.handleListSearch} value={this.state.searchTerm} type=”text” placeholder={this.props.placeholder} /&gt;</strong><br> <br> &lt;/div&gt;<br> <strong>&lt;WrappedComponent list={this.state.filteredData} /&gt;</strong><br> &lt;/div&gt;<br> )<br> }</pre><p>If we take a look at the above code, the WrappedComponent would receive the data through the ‘this.state.filteredData’. Also we have added a function call to ‘handleListSearch’ that would perform the search/filter based on the input value. Also, a placeholder text has been that we would receive as props.</p><p>Now, inside the handleListSearch function, we could use Array.filter() function to return the list of marching values based on the input/search box value. Our code for handleSearch could be written as follows:</p><pre>handleListSearch = event =&gt; {<br> <br> let searchTerm= event.target.value;<br> let self=this;<br> let filteredData = <strong>this.props.list.filter(function(item){<br> if(item[self.props.field].toUpperCase().indexOf(searchTerm.toUpperCase()) &gt;= 0)<br> return item<br> <br> });</strong><br> this.setState({filteredData: filteredData, searchTerm: event.target.value})<br> }</pre><p>We get the value of the input/search box as searchTerm and perform a filter operation and store the result in filteredData variable. Once we got the result, we store the filteredData and searchTerm in state where filteredData would be sent back to the WrappedComponent and searchTerm is used to display the text in input box.</p><p>Final code for our SearchListHOC.jsx can be written as follows:</p><pre>const SearchList = (WrappedComponent) =&gt; {<br> return class extends React.Component {<br> constructor(props) {<br> super(props);<br> this.state = {<br> searchTerm: ‘’,<br> filteredData: props.list<br> }<br> }<br> handleListSearch = event =&gt; {<br> <br> let searchTerm= event.target.value;<br> let self=this;<br> let filteredData = this.props.list.filter(function(item){<br> if(item[self.props.field].toUpperCase().indexOf(searchTerm.toUpperCase()) &gt;= 0)<br> return item<br> <br> });<br> this.setState({filteredData: filteredData, searchTerm: event.target.value})<br> }</pre><pre>render() {<br> return (<br> &lt;div&gt;<br> &lt;div&gt;<br> &lt;input onChange={this.handleListSearch} value={this.state.searchTerm} type=”text” placeholder={this.props.placeholder} /&gt;<br> <br> &lt;/div&gt;<br> &lt;WrappedComponent list={this.state.filteredData} /&gt;<br> &lt;/div&gt;<br> )<br> }<br> }<br> <br>}<br>export default SearchList</pre><p>For displaying the Table, I will be using the same code from my <a href="https://medium.com/@subalerts/create-dynamic-table-from-json-in-react-js-1a4a7b1146ef">another article</a>. Please refer to the other article for more information regarding the Table component.</p><p>Using the same code from Table component that would dynamically create table based on json value sent:</p><pre>export default class Table extends React.Component {<br> <br> constructor(props){<br> super(props);<br> this.getHeader = this.getHeader.bind(this);<br> this.getRowsData = this.getRowsData.bind(this);<br> this.getKeys = this.getKeys.bind(this);<br> }<br> <br> getKeys = function(){<br> return this.props.data.length&gt;0?Object.keys(this.props.data[0]):[];<br> }<br> <br> getHeader = function(){<br> var keys = this.getKeys();<br> return keys.map((key, index)=&gt;{<br> return &lt;th key={key}&gt;{key.toUpperCase()}&lt;/th&gt;<br> })<br> }<br> <br> getRowsData = function(){<br> var items = this.props.data;<br> var keys = this.getKeys();<br> return items.map((row, index)=&gt;{<br> return &lt;tr key={index}&gt;&lt;RenderRow key={index} data={row} keys={keys}/&gt;&lt;/tr&gt;<br> })<br> }<br> <br> render() {<br> return (<br> &lt;div&gt;<br> &lt;table&gt;<br> &lt;thead&gt;<br> &lt;tr&gt;{this.getHeader()}&lt;/tr&gt;<br> &lt;/thead&gt;<br> &lt;tbody&gt;<br> {this.getRowsData()}<br> &lt;/tbody&gt;<br> &lt;/table&gt;<br> &lt;/div&gt;<br> <br> );<br> }<br>}</pre><pre>const RenderRow = (props) =&gt;{<br> return props.keys.map((key, index)=&gt;{<br> return &lt;td key={props.data[key]}&gt;{props.data[key]}&lt;/td&gt;<br> })<br>}</pre><p>In App.jsx we will create json that would form the table and pass it to MyList component which will be wrapped around the SearchListHOC that has been created. Also, we will be sending the placeholder text and the filed name on which search operation should be performed. Code for App.jsx will be as follows:</p><pre>export default class App extends React.Component {<br> <br> constructor(props){<br> super(props);<br> this.state = {<br> “itemsList1”:[<br> {“fruit”: “Apple”, “cost”: “80”},<br> {“fruit”: “Banana”, “cost”: “50”},<br> {“fruit”: “Orange”, “cost”: “40”},<br> {“fruit”: “Grapes”, “cost”: “40”},<br> {“fruit”: “Carrot”, “cost”: “65”},<br> {“fruit”: “Papaya”, “cost”: “73”},<br> {“fruit”: “Mango”, “cost”: “100”}<br> ],<br> “itemsList2”:[<br> {<br> “name”: “John”,<br> “city”: “chicago”,<br> “age”: “22”<br> },<br> {<br> “name”: “Gary”,<br> “city”: “florida”,<br> “age”: “35”<br> },<br> {<br> “name”: “Selena”,<br> “city”: “vegas”,<br> “age”: “18”<br> }<br> ]<br> }<br> }<br> <br> render() {<br> console.log(MyList)<br> <br> return (<br> &lt;div className=”App”&gt;<br> Hello, React<br> &lt;h1&gt; Item List 1&lt;/h1&gt;<br> &lt;MyList list = {this.state.itemsList1} field={‘fruit’} placeholder={‘Search fruits’}/&gt;<br> &lt;br/&gt;<br> &lt;h1&gt; Item List 2&lt;/h1&gt;<br> &lt;MyList list = {this.state.itemsList2} field={‘name’} placeholder={‘Search Name’}/&gt;<br> &lt;/div&gt;<br> <br> );<br> }<br>}</pre><p>Last, MyList.jsx will be a component that would wrap around our SearchListHOC and internally would use the Table.jsx to display the table data ( that would be returned form HOC). Code for MyList.jsx can be written as follows:</p><pre>import React from ‘react’;<br>import SearchList from ‘./SearchListHOC.jsx’;<br>import Table from ‘./Table.jsx’;</pre><pre>class MyList extends React.Component {<br> constructor(props){<br> super(props);<br> }<br> <br> render() {<br> return (<br> &lt;div&gt;<br> &lt;Table data={this.props.list}/&gt;<br> &lt;/div&gt;<br> <br> );<br> }<br>}</pre><pre>export default SearchList(MyList)</pre><p>This finished all of our components. If we run the application in browser, we could see two tables, that would have a search box placed on top of them. On any search operation performed, we could see the Table data gets updated accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*yeG-SNIxj-Cj67tFxBJzJQ.png" /><figcaption>Example of Search HOC</figcaption></figure><p>Working example of the same can be found in the following <a href="https://plnkr.co/edit/IOnv4bb59OuSoULpySHh?p=preview">plunker</a></p><p>Happy learning :)</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b26bfe3a7d26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Dynamic Table from json in react js]]></title>
            <link>https://medium.com/@subalerts/create-dynamic-table-from-json-in-react-js-1a4a7b1146ef?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a4a7b1146ef</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-dynamic-table]]></category>
            <category><![CDATA[react-json-table]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-table]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Fri, 10 May 2019 15:31:42 GMT</pubDate>
            <atom:updated>2019-05-10T15:31:42.413Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will see how we can create a table dynamically from any json (one level) using react js. All that we have to do is pass a json data as a property to the component and our component should be able to display the data in a tabular form.</p><p>By the end of the article we will be creating a component that will be used as follows:</p><pre>&lt;Table data={this.state.data}/&gt;</pre><p>The json data that would be sent can be anything similar to the following format (a list of objects containing key, values):</p><pre>[<br> {‘fruit’: ‘Apple’, ‘cost’: 100},<br> {‘fruit’: ‘Orange’, ‘cost’: 50},<br> {‘fruit’: ‘Banana’, ‘cost’: 35},<br> {‘fruit’: ‘Mango’, ‘cost’: 70},<br> {‘fruit’: ‘Pineapple’, ‘cost’: 45},<br> {‘fruit’: ‘Papaya’, ‘cost’: 40},<br> {‘fruit’: ‘Watermelon’, ‘cost’: 35}<br> ]</pre><pre>or</pre><pre>[<br>          {&#39;Name&#39;: &#39;Abc&#39;, &#39;Age&#39;: 15, &#39;Location&#39;: &#39;Bangalore&#39;},<br>          {&#39;Name&#39;: &#39;Def&#39;, &#39;Age&#39;: 43, &#39;Location&#39;: &#39;Mumbai&#39;},<br>          {&#39;Name&#39;: &#39;Uff&#39;, &#39;Age&#39;: 30, &#39;Location&#39;: &#39;Chennai&#39;},<br>          {&#39;Name&#39;: &#39;Ammse&#39;, &#39;Age&#39;: 87, &#39;Location&#39;: &#39;Delhi&#39;},<br>          {&#39;Name&#39;: &#39;Yysse&#39;, &#39;Age&#39;: 28, &#39;Location&#39;: &#39;Hyderabad&#39;}<br>      ]</pre><p>Now, let’s start by creating our component. In the component there will be three functions that would do the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Aa9suvaNqCgrGZjN2lKg5w.png" /></figure><p><strong>getKeys function</strong>: This function would return the list of headings that should be displayed on top of the table. We would fetch these values form the ‘key’ that is passed in the json.</p><p><strong>getHeader function: </strong>This function would contain the logic that would return the header (component) part of the table</p><p><strong>getRowsData function: </strong>This would contain the logic (where we would iterate through the json) and return the body part of the table.</p><p><strong>renderRow component: </strong>This component would contain the logic where the columns of a particular row will be returned.</p><p>If we setup a code with the above requirements, our code would be as follows:</p><pre>export default class Table extends React.Component {<br> <br> constructor(props){<br> super(props);<br><strong> </strong>this.getHeader = this.getHeader.bind(this);<br> this.getRowsData = this.getRowsData.bind(this);<br> this.getKeys = this.getKeys.bind(this);<br> }<br> <br> getKeys = function(){<br><br> }<br> <br> getHeader = function(){<br> <br> }<br> <br> getRowsData = function(){<br> <br> }<br> <br> <strong>render() {<br> return (<br> &lt;div&gt;<br> &lt;table&gt;<br> &lt;thead&gt;<br> &lt;tr&gt;{this.getHeader()}&lt;/tr&gt;<br> &lt;/thead&gt;<br> &lt;tbody&gt;<br> {this.getRowsData()}<br> &lt;/tbody&gt;<br> &lt;/table&gt;<br> &lt;/div&gt;<br> <br> );</strong><br> }<br>}</pre><pre>const RenderRow = (props) =&gt;{<br> <br>}</pre><p>Take a look at the render() part. We have written a basic skeleton of a <a href="https://www.w3schools.com/tags/tag_thead.asp">table</a> and replaced the head and body part of it with functions that would return the elements generated dynamically form the json data.</p><p>In order to generate the header element, we would need the keys/headings that are required. Since we are passing a list of json objects containing key value pairs, the keys that we send can be used as a the column header values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*aPJ4wIMJLgjz_Wa4gbXamQ.png" /></figure><p>In the example beside, ‘fruit ’and ‘cost ’will be our heading values. As we can see, since the data format is same, we need not iterate through the entire list to get the header values. We can simply take the first object and get the keys form it.</p><p>Based on the above, our getKeys() function can be written as follows, where Object.keys function below is the in-built javascript function to get the keys from any object:</p><pre>getKeys = function(){<br> return <strong>Object.keys(this.props.data[0]);</strong><br> }</pre><p>As we got the keys now, next step now is to iterate through the keys and return the &lt;th&gt;&lt;/th&gt; element as the heading for the header part. Our getHeader() function can be written as follows:</p><pre>getHeader = function(){<br> var keys = this.getKeys();<br> return <strong>keys.map((key, index)=&gt;{<br> return &lt;th key={key}&gt;{key.toUpperCase()}&lt;/th&gt;<br> })</strong><br> }</pre><p>Notice the usage of keys.map function where we are iterating through all the keys and returning headings.</p><p>Next step is to complete the renderRow component. We will be passing the row data and keys data to the component. If we iterate through the key values, data[keyValue] would give us the corresponding column value from the json. According to this, our component would be as follows:</p><pre>const RenderRow = (props) =&gt;{<br> return props.keys.<strong>map((key, index)=&gt;{<br> return &lt;td key={props.data[key]}&gt;{props.data[key]}&lt;/td&gt;<br> })</strong><br>}</pre><p>Last step is to complete the getRowsData function where, we would iterate through all the list items and use the RenderRow component created inside so that it would return the all the row components.</p><pre>getRowsData = function(){<br> var items = this.props.data;<br> var keys = this.getKeys();<br> return items.<strong>map((row, index)=&gt;{<br> return &lt;tr key={index}&gt;&lt;RenderRow key={index} data={row} keys={keys}/&gt;&lt;/tr&gt;<br> })</strong><br> }</pre><p>A little styling has to be done to make the table look better. Let us add a little border and color as follows:</p><pre>thead {color:green;}<br>tbody {color:blue;}</pre><pre>table, th, td {<br> border: 1px solid black;<br>}<br>td, th{<br> padding: 5px;<br>}</pre><p>This finishes our table component. Now our component can be imported in any jsx and ready for use. Sample page with the json provided above would look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*RwzK59P9eztNUoWIDHEM6g.png" /></figure><p>Working example of the same can be found in the following <a href="https://plnkr.co/edit/ysN4Qb3lUp9mbqFhumWJ?p=preview">plunker</a></p><p>Happy learning :)</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a4a7b1146ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing custom context menu in react.js]]></title>
            <link>https://medium.com/@subalerts/https-medium-com-implementing-custom-context-menu-in-react-js-part-1-b103260c724c?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b103260c724c</guid>
            <category><![CDATA[context]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[menu]]></category>
            <category><![CDATA[context-menus]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Wed, 01 May 2019 12:36:20 GMT</pubDate>
            <atom:updated>2019-07-08T09:14:39.200Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of this article, we would write the code to implement the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*h9s4Y0K5DrdIbYmqoEUelw.gif" /><figcaption>custom context menu in react js</figcaption></figure><p>In this article, we will look at how we can override the default browser’s context menu and replace it with our own in react.js.</p><p>Since we are talking about context menu, first we have to figure out how to capture the context menu / right click event in javascript. Then, we have to disable the browser default one with our own menu.</p><p>In order to capture the right click event from the browser, we have to listen to the ‘contextmenu’ event from the browser window. Once the event is captured, disable the default action performed. Javascript code for the same can be written as follows</p><pre>document.addEventListener(‘contextmenu’, function(event){<br> event.preventDefault();})</pre><p>Now, we have to capture the x,y coordinates and add our own menu at that particular position on the page.</p><p>Now, let us start writing our component. We will be creating a component called ‘CustomContext’ and pass menu items as ‘items’ property. For this example, I will be passing the following json as the list of items to be displayed in the context menu. We store these values in the state.</p><pre>menu = [{“label”:”Item 1&quot;},{“label”:”Menu item 2&quot;},{“label”:”Apple”},{“label”:”This is orange”},{“label”:”Conetxt menu is fun”},{“label”:”Cool”}]</pre><p>We can add the context menu to the page using the following code:</p><pre>&lt;CustomContext <strong>items={this.state.menu}</strong>&gt;<br> &lt;/CustomContext&gt;</pre><p>Let us start writing the CustomContext component. We will be adding the eventListener in the componentDidMount(), write logic to convert the list to a menu and update the x,y position based on mouse click. Also, if a left click is done, we will hide the menu.</p><p>Code for the same will be as follows:</p><pre>class CustomContext extends React.Component{<br> constructor(props) {<br> super(props);<br> <br> this.state={<br> visible: false,<br> x: 0,<br> y: 0<br> };<br> }<br> <br> componentDidMount(){<br> var self=this;<br> document.addEventListener(‘contextmenu’, function(event){<br> event.preventDefault();<br> const clickX = event.clientX;<br> const clickY = event.clientY;<br> self.setState({ visible: true, x: clickX, y: clickY });<br> <br> });<br> document.addEventListener(‘click’, function(event){<br> event.preventDefault();<br> self.setState({ visible: false, x:0, y:0});<br> <br> });<br> }<br> <br> returnMenu(items){<br> <strong>var myStyle = {<br> ‘position’: ‘absolute’,<br> ‘top’: `${this.state.y}px`,<br> ‘left’:`${this.state.x+5}px`<br> }</strong><br> <br> return &lt;div className=’custom-context’ id=’text’<strong> style={myStyle}</strong>&gt;<br> {items.map((item, index, arr) =&gt;{<br> if(arr.length-1==index){<br> return &lt;div key={index} className=’custom-context-item-last’&gt;{item.label}&lt;/div&gt;<br> }else{<br> return &lt;div key={index} className=’custom-context-item’&gt;{item.label}&lt;/div&gt;<br> }<br> })}<br> &lt;/div&gt;;<br> }</pre><p>In the componentDidMount function, we have added event listener for ‘contextmenu’ which gets called when right click is done on the page. Inside the function, we have stopped the default action using event.preventDefault() and set the visibility to true and updated the x,y coordinates to the clicked position. Also, for the click event listener, we are setting x,y values to 0,0 and set the visibility to false so that our context menu would be hidden.</p><p>Next is the returnMenu() function that accepts the list of items as the parameter. We wrap the items in an outer div with id ‘text’, iterate the list using map function and add as a childern. Also, the style of the outer div has been updated such that it would be placed at the x,y position that has been already set.</p><p>Little css styling has been done such that the menu items appear with dotted bottom border (except the last one) and surrounded by a box with some padding.</p><p>Here is the css for the same:</p><pre>.custom-context{<br> border: solid 1px #ccc;<br> display: inline-block;<br> margin: 5px;<br> background: #FFF;<br> color: #000;<br> font-family: sans-serif;<br> cursor: pointer;<br> font-size: 12px;<br>}<br>.custom-context-item{<br> border-bottom: dotted 1px #ccc;<br> padding: 5px 25px;<br>}<br>.custom-context-item-last{<br> padding: 5px 25px;<br>}</pre><p>Now, the last part, a condition has to be written in the render block such that if the visibility value is true, we display the div/context menu created.</p><pre>render() {<br> return (&lt;div id=’cmenu’&gt;<br><strong> {this.state.visible ? this.returnMenu(this.props.items): null}</strong><br> &lt;/div&gt;<br> )<br> }</pre><p>Now that our context menu has been in place, we will look at how we can perform some action on clicking on the menu item.</p><p>In order to add the callbacks for the context menu items, let’s add a callback property to the items list in the state and also add the corresponding functions as follows in the main class in which the CustomContext component has been loaded. Here, we just added alert boxes to check if the functionality works</p><pre>this.state={<br> “menu”:[<br> {“label”: “Item 1”, <strong>“callback”: this.itemCallback</strong>},<br> {“label”: “Menu item 2”, <strong>“callback”: this.item2Callback</strong>},<br> {“label”: “Apple”, <strong>“callback”: this.appleCallback</strong>},<br> {“label”: “This is orange”, <strong>“callback”: this.orangeCallback</strong>},<br> {“label”: “Conetxt menu is fun”, },<br> {“label”: “Cool”, <strong>“callback”: this.coolCallback</strong>}<br> ]<br> }<br> }<br> <br> itemCallback() {<br> alert(“clicked on Item 1”)<br> }<br> <br> item2Callback() {<br> alert(“clicked on Item 2”)<br> }<br> <br> appleCallback() {<br> alert(“clicked on Apple”)<br> }<br> orangeCallback() {<br> alert(“clicked on Orange”)<br> }<br> coolCallback(){<br> alert(“clicked on Cool”)<br> }</pre><p>Update the return statement of returnMenu() function with ref and index as follows:</p><pre>return &lt;div className=’custom-context’ <strong>id=’customcontext’</strong> style={myStyle}<strong> ref={this.contextRef}</strong>&gt;<br> {items.map((item, index, arr) =&gt;{<br> <br> if(arr.length-1==index){<br> return &lt;div key={index} className=’custom-context-item-last’ <strong>index={index}</strong>&gt;{item.label}&lt;/div&gt;<br> }else{<br> return &lt;div key={index} className=’custom-context-item’ <strong>index={index}</strong>&gt;{item.label}&lt;/div&gt;<br> }<br> })}<br> &lt;/div&gt;;</pre><p>As we could see, a reference has been added to the outer container of the context menu and a new attribute, index has been added which would be used in the function where click event has been captured.</p><p>Now, let us update the code of the click event listener as follows:</p><pre>document.addEventListener(‘click’, function(event){<br> <br> <strong>if(self.contextRef.current.id==’customcontext’){<br> self.click(event.target.getAttribute(‘index’));<br> }</strong><br> event.preventDefault();<br> self.setState({ visible: false, x:0, y:0});<br> <br> });</pre><p>Here, we are checking if the id of the container clicked equals ‘customcontext’ which is the id of the outer container of our context menu. If the condition matches, we get the index of the clicked div and pass the value to another function called click.</p><p>Inside the click function, we can invoke the callback function that has been passed to the child using props.item.</p><p>Our click function would be as follows (with a little check added for checking if callback is present for the menu item):</p><pre>click(index) {<br> if(this.props.items[index].callback)<br><strong> this.props.items[index].callback();</strong><br> else{<br> console.log(“callback not registered for the menu item”)<br> }<br> }</pre><p>Our custom component is now ready with our own actions. We could define the functionality of the context menu item in parent component and use the ‘callback’ key to pass the values to the child as a property.</p><p>Working example of the same can be found in the following <a href="http://plnkr.co/edit/8Q3GOQPfTbIdHtcf4qiq?p=preview">plunker</a></p><p>Next Steps: I have done the basic context menu which contains only one level. Code can be updated to support sub-menus as well where we should be able to provide the data using nested json and update the returnMenu() function to display the nested items which should be easier to implement on top of this.</p><p>Happy Learning :-)</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b103260c724c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Protected routes in React JS]]></title>
            <link>https://medium.com/@subalerts/creating-protected-routes-in-react-js-89e95974a822?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e95974a822</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[protected-routing]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[react-routing]]></category>
            <category><![CDATA[react-development]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 07:20:39 GMT</pubDate>
            <atom:updated>2019-03-27T07:20:39.970Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story we would write create a basic react app with routing and create a protected route where only authorized users will be able to access it.</p><p>First of all create an app using create-react-app and install react-router-dom</p><blockquote>create-react-app protected-routes<br>npm install react-router-dom</blockquote><p>There are 3 important steps to use react-router.</p><ol><li>We have to wrap our application inside {BrowserRouter} from react-router-dom</li><li>Define our routes using {Route} component</li><li>Link routes using {Link} component</li></ol><p>Addition to these, to create a protected-route we will do the following:</p><p>4. Create a fake authentication service</p><p>5. Create a protected Route component and check for user validation using the fake authentication service</p><p>Now, let us wrap our application inside BrowserRouter according to setp 1. Open index.js file and import the BorwserRouter component form react-router-dom and wrap the &lt;App/&gt; component inside it</p><pre>import {BrowserRouter} from ‘react-router-dom’;<br>ReactDOM.render(<br>&lt;BrowserRouter&gt;&lt;App /&gt;<br>&lt;/BrowserRouter&gt;, document.getElementById(‘root’));</pre><p>Create two separate components for Public and Private routes which will be used for our routing purpose. Our code for Public.js and Private.js can be as follows:</p><pre>import React from &#39;react&#39;;</pre><pre>const Public =() =&gt; {</pre><pre>return &lt;h1&gt; This is a Public route&lt;/h1&gt;</pre><pre>}</pre><pre>export default Public;</pre><p>Similarly Private.js file can be created</p><p>Now, let’s add a new file called Router.js and add the routes</p><pre>import React, {Component} from &#39;react&#39;;</pre><pre>import { Switch, Route, Redirect } from &#39;react-router-dom&#39;;</pre><pre>import Public from &#39;./components/Public&#39;;</pre><pre>import Protected from &#39;./components/Protected&#39;;</pre><pre>const Router = (props) =&gt; (</pre><pre><strong>&lt;Switch&gt;</strong></pre><pre><strong>&lt;Route exact path=&#39;/public&#39; component={Public}/&gt;</strong></pre><pre><strong>&lt;Route path=&quot;/protected&quot; component={Protected} /&gt;</strong></pre><pre><strong>&lt;/Switch&gt;</strong></pre><pre>)</pre><pre>export default Router;</pre><p>Let us add a file called Header.js that has three links for Home, Public and Protected and two buttons to login and logout</p><pre>import React from &#39;react&#39;;</pre><pre>import { Link } from &#39;react-router-dom&#39;;</pre><pre>class Header extends React.Component{</pre><pre>constructor(props){</pre><pre>super(props);</pre><pre>this.login=this.login.bind(this);</pre><pre>this.logout=this.logout.bind(this);</pre><pre>}</pre><pre>login(){</pre><pre>}</pre><pre>logout(){</pre><pre>}</pre><pre>render(){</pre><pre>return(</pre><pre>&lt;div&gt;</pre><pre>&lt;Link to=&#39;/&#39;&gt;Home&lt;/Link&gt;&lt;br/&gt;</pre><pre>&lt;Link to=&#39;Public&#39;&gt;Public&lt;/Link&gt;&lt;br/&gt;</pre><pre>&lt;Link to=&#39;protected&#39;&gt;Protected&lt;/Link&gt;&lt;br/&gt;</pre><pre>&lt;button onClick={this.login}&gt;Login&lt;/button&gt;&lt;br/&gt;</pre><pre>&lt;button onClick={this.logout}&gt;Logout&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>export default Header;</pre><p>Next step is to update the App.js file to include our header and router</p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre>import  Header from &#39;./components/Header&#39;;</pre><pre>import Router from &#39;./Router&#39;;</pre><pre>class App extends Component {</pre><pre>render() {</pre><pre>return (</pre><pre>&lt;div className=&quot;App&quot;&gt;</pre><pre><strong>&lt;Header/&gt;</strong></pre><pre><strong>&lt;Router/&gt;</strong></pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>export default App;</pre><p>At this step we have created a basic app with Routes set up. Our page looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*ZK2vb2XGCWO48pPTxAJW-Q.png" /></figure><p>Now that we have finished the basic app with routes, let us add a fake authentication service and update the Header.js and Routes.js files to be able to use protected routes</p><p>Create a file called Auth.js and add the following code</p><pre>const Auth = {</pre><pre>isAuthenticated: false,</pre><pre>authenticate() {</pre><pre>this.isAuthenticated = true;</pre><pre>},</pre><pre>signout() {</pre><pre>this.isAuthenticated = false;</pre><pre>},</pre><pre>getAuth() {</pre><pre>return this.isAuthenticated;</pre><pre>}</pre><pre>};</pre><pre>export default Auth;</pre><p>Now, we need to update the Router.js file. We will be creating a component called PrivateRoute which would accept the component to which application has to route if the user has authenticated. Otherwise user will be redirected to home page. And finally update the Route that we used to the newly created protected route.</p><p>The final code of Router.js will be as follows. Notice the creation of Private Route and usage of the App component that was created.</p><pre>import React, {Component} from &#39;react&#39;;</pre><pre>import { Switch, Route, Redirect } from &#39;react-router-dom&#39;;</pre><pre>import Public from &#39;./components/Public&#39;;</pre><pre>import Protected from &#39;./components/Protected&#39;;</pre><pre><strong>import Auth from &#39;./Auth&#39;;</strong></pre><pre>const Router = (props) =&gt; (</pre><pre>&lt;Switch&gt;</pre><pre>&lt;Route exact path=&#39;/public&#39; component={Public}/&gt;</pre><pre>&lt;<strong>PrivateRoute</strong> path=&quot;/protected&quot; component={Protected} /&gt;</pre><pre>&lt;/Switch&gt;</pre><pre>)</pre><pre><strong>const PrivateRoute = ({ component: Component, ...rest }) =&gt; (</strong></pre><pre><strong>&lt;Route</strong></pre><pre><strong>{...rest}</strong></pre><pre><strong>render={props =&gt;</strong></pre><pre><strong>Auth.getAuth() ? (</strong></pre><pre><strong>&lt;Component {...props} /&gt;</strong></pre><pre><strong>) : (</strong></pre><pre><strong>&lt;Redirect</strong></pre><pre><strong>to={{</strong></pre><pre><strong>pathname: &quot;/&quot;</strong></pre><pre><strong>}}</strong></pre><pre><strong>/&gt;</strong></pre><pre><strong>)</strong></pre><pre><strong>}</strong></pre><pre><strong>/&gt;</strong></pre><pre><strong>);</strong></pre><pre>export default Router;</pre><p>Last, we need to update the Header.js file so that we will be able to update the login/logout state based on the button click.</p><pre>import React from &#39;react&#39;;</pre><pre>import { Link } from &#39;react-router-dom&#39;;</pre><pre>import Auth from &#39;../Auth&#39;;</pre><pre>class Header extends React.Component{</pre><pre>constructor(props){</pre><pre>super(props);</pre><pre><strong>this.login=this.login.bind(this);</strong></pre><pre><strong>this.logout=this.logout.bind(this)</strong>;</pre><pre>}</pre><pre><strong>login(){</strong></pre><pre><strong>Auth.authenticate();</strong></pre><pre><strong>}</strong></pre><pre><strong>logout(){</strong></pre><pre><strong>Auth.signout();</strong></pre><pre><strong>}</strong></pre><pre>render(){</pre><pre>return(</pre><pre>&lt;div&gt;</pre><pre>&lt;Link to=&#39;/&#39;&gt;Home&lt;/Link&gt;&lt;br/&gt;</pre><pre>&lt;Link to=&#39;Public&#39;&gt;Public&lt;/Link&gt;&lt;br/&gt;</pre><pre>&lt;Link to=&#39;protected&#39;&gt;Protected&lt;/Link&gt;&lt;br/&gt;</pre><pre><strong>&lt;button onClick={this.login}&gt;Login&lt;/button&gt;&lt;br/&gt;</strong></pre><pre><strong>&lt;button onClick={this.logout}&gt;Logout&lt;/button&gt;</strong></pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>export default Header;</pre><p>Once the app is run, if the user clicks on Login button and try to navigate the the protected route, routing would happen. If the user is Logged out or not signed in, clicking on protected route would redirect the user to home page.</p><p>Here is a working example of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*UebXuFESbqLZpGT05_mCtg.gif" /></figure><p>Source code of the above example can be downloaded form the following <a href="https://github.com/TarakeshS/protected-routes">github page</a></p><p>Happy Learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e95974a822" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React.js updating parent’s state from child component]]></title>
            <link>https://medium.com/@subalerts/react-js-updating-parents-state-from-child-component-86595ad2c1ff?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/86595ad2c1ff</guid>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[child-to-parent]]></category>
            <category><![CDATA[update-parent]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 10:03:53 GMT</pubDate>
            <atom:updated>2019-03-26T10:03:53.094Z</atom:updated>
            <content:encoded><![CDATA[<p>We would write a basic example having a parent component and a child component. Parent component would have a counter value. Child component contains two buttons, increment and decrement. Upon clicking the button we would update the counter value of parent accordingly.</p><p>First we would create a parent component called App and initialize it with a counter value to 0. Also we define a function called updateCounter that would either increase or decrease the value based on the parameter passed.</p><p>So, our parent component would be as follows:</p><blockquote>class App extends React.Component {<br> constructor(props) {<br> super(props);<br> this.state = {<br> counter: 0<br> }<br> this.updateCounter = this.updateCounter.bind(this);<br> <br> }<br> updateCounter(type){<br> var count = this.state.counter;<br> type==’increment’? count++: count — ;<br> this.setState({counter: count});<br> }<br> <br> render() {<br> return (&lt;div&gt;<br> Value of counter in parent is {this.state.counter}<br><br> &lt;/div&gt;<br> )<br> }<br>}</blockquote><p>Now we would create a child component that has 2 buttons.</p><blockquote>class Child extends React.Component{<br> constructor(props) {<br> super(props);<br> }<br> render() {<br> return (&lt;div&gt;<br> &lt;h1&gt;Hello, React..&lt;/h1&gt;<br> &lt;p&gt;I am form child and the buttons below are fom child. Click on the corresponding buttom to update counter value in parent&lt;/p&gt;<br> &lt;button&gt;Increment&lt;/button&gt;&lt;br/&gt;&lt;br/&gt;<br> &lt;button&gt;Decrement&lt;/button&gt;<br> <br> &lt;/div&gt;<br> )<br> }<br> <br>}</blockquote><p>Now, in order to make the updateCounter function in parent to be available to the child component, we pass it as a property to the child component. Render block in our Parent/App component can be updated as follows:</p><blockquote>render() {<br> return (&lt;div&gt;<br> Value of counter in parent is {this.state.counter}<br> &lt;Child onClick={this.updateCounter}/&gt;<br> &lt;/div&gt;<br> )<br> }</blockquote><p>In order to use the function in child component, now we can simply use {this.props.onClick} on button click in the child component and pass the corresponding parameter</p><p>Our render block would appear as follows:</p><blockquote>render() {<br> return (&lt;div&gt;<br> &lt;h1&gt;Hello, React..&lt;/h1&gt;<br> &lt;p&gt;I am form child and the buttons below are fom child. Click on the corresponding buttom to update counter value in parent&lt;/p&gt;<br> &lt;button onClick={(e) =&gt; this.props.onClick(‘increment’)}&gt;Increment&lt;/button&gt;&lt;br/&gt;&lt;br/&gt;<br> &lt;button onClick={(e) =&gt; this.props.onClick(‘decrement’)}&gt;Decrement&lt;/button&gt;<br> <br> &lt;/div&gt;<br> )<br> }</blockquote><p>Final code:</p><blockquote>class App extends React.Component {<br> constructor(props) {<br> super(props);<br> this.state = {<br> counter: 0<br> }<br> this.updateCounter = this.updateCounter.bind(this);<br> <br> }<br> updateCounter(type){<br> var count = this.state.counter;<br> type==’increment’? count++: count — ;<br> this.setState({counter: count});<br> }<br> <br> render() {<br> return (&lt;div&gt;<br> Value of counter in parent is {this.state.counter}<br> &lt;Child onClick={this.updateCounter}/&gt;<br> &lt;/div&gt;<br> )<br> }<br>}</blockquote><blockquote>class Child extends React.Component{<br> constructor(props) {<br> super(props);<br> }<br> render() {<br> return (&lt;div&gt;<br> &lt;h1&gt;Hello, React..&lt;/h1&gt;<br> &lt;p&gt;I am form child and the buttons below are fom child. Click on the corresponding buttom to update counter value in parent&lt;/p&gt;<br> &lt;button onClick={(e) =&gt; this.props.onClick(‘increment’)}&gt;Increment&lt;/button&gt;&lt;br/&gt;&lt;br/&gt;<br> &lt;button onClick={(e) =&gt; this.props.onClick(‘decrement’)}&gt;Decrement&lt;/button&gt;<br> <br> &lt;/div&gt;<br> )<br> }<br> <br>}</blockquote><p>Working example of the same can be found in the following <a href="https://plnkr.co/edit/3k8ZOfXQDKbGIYqLh0le?p=preview">plunker</a></p><p>Demo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*zQtI_k_c3SSEOAiudADtCw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86595ad2c1ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implememting a simple Collapsible component in React JS]]></title>
            <link>https://medium.com/@subalerts/implememting-a-simple-collapsible-component-in-react-js-67c796e64652?source=rss-1b01c46cc3b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/67c796e64652</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[collapsible]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactcollapsible]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Tarak]]></dc:creator>
            <pubDate>Fri, 14 Dec 2018 06:07:37 GMT</pubDate>
            <atom:updated>2018-12-14T06:07:37.185Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explains how we can create a simple collapsible component in react js. We will be passing the heading as a property to the component and the jsx that gets wrapped inside the component would be toggled on click of header.</p><p>First, let us start creating a simple component. We will be using a state variable called ‘open’ which would be set to true/false based on which we will be showing/hiding content. Also let us add a function called togglePanel which would be used to set the state to true/false</p><p>Our base component would look as follows:</p><blockquote>class Collapsible extends React.Component {<br> constructor(props){<br> super(props);<br> this.state = {<br> open: false<br> }<br> this.togglePanel = this.togglePanel.bind(this);<br> }</blockquote><blockquote>togglePanel(e){<br> this.setState({open: !this.state.open})<br> }</blockquote><blockquote>render() {<br> return (&lt;div&gt;<br> // Code for collapsible would be added here<br> &lt;/div&gt;);<br> }<br> }</blockquote><p>Now, let us update the render portion of the above code. As mentioned above, we would get the title as prop from the parent component. In react, we can use {this.props.children} to get the jsx that is wrapped inside any component. Also, as mentioned above, we will be using {this.state.open} to show/hide the content. We will be writing a conditional statement in the render portion such that if {this.state.open} equals to true we would show the children. Else children would not be displayed.</p><p>Our updated render part looks as follows:</p><blockquote>render() {<br> return (&lt;div&gt;<br> &lt;div &gt;{this.props.title}&lt;/div&gt;<br> {this.state.open ? (&lt;div&gt;{this.props.children}&lt;/div&gt;) : null}</blockquote><blockquote>&lt;/div&gt;);<br> }</blockquote><p>Next step is to add toggle functionality. Since we already defined the togglePanel() function, we can call the function on click of the header div and toggle the state. Once the stage gets toggled, react would re-render the component and based on the state, the child content would be shown/hidden.</p><p>Also, we can add CSS classes to make the header and content look better.</p><p>Our final code will be as follows:</p><blockquote>// Collapsible.js</blockquote><blockquote>class Collapsible extends React.Component {<br> constructor(props){<br> super(props);<br> this.state = {<br> open: false<br> }<br> this.togglePanel = this.togglePanel.bind(this);<br> }</blockquote><blockquote>togglePanel(e){<br> this.setState({open: !this.state.open})<br> }</blockquote><blockquote>render() {<br> return (&lt;div&gt;<br> &lt;div onClick={(e)=&gt;this.togglePanel(e)} className=’header’&gt;<br> {this.props.title}&lt;/div&gt;<br> {this.state.open ? (<br> &lt;div className=’content’&gt;<br> {this.props.children}<br> &lt;/div&gt;<br> ) : null}<br> &lt;/div&gt;);<br> }<br> }<br> <br> /* CSS */</blockquote><blockquote>.header{<br> cursor: pointer;<br> border: solid 1px #f2f2f2;<br> padding: 15px;<br> background-color: #0089CC;<br> color: #FFF;<br> font-family: verdana;<br>}</blockquote><blockquote>.content{<br> cursor: pointer;<br> border-left: solid 1px #f2f2f2;<br> border-right: solid 1px #f2f2f2;<br> border-bottom: solid 1px #f2f2f2;<br> border-radius: 0 0 5px 5px;<br> padding: 15px;<br> font-family: verdana;<br> font-size: 14px;<br>}</blockquote><p>Output of the above code would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*hEi5IxxtrXKlJ7vTF9hikg.gif" /></figure><p>Working example for the same can be found in the following <a href="https://plnkr.co/edit/rkpe3f?p=preview">plunker</a></p><p>Thank you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67c796e64652" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>