<?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 Aprajita on Medium]]></title>
        <description><![CDATA[Stories by Aprajita on Medium]]></description>
        <link>https://medium.com/@stressed83?source=rss-68974d81f333------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a9lb3ZN9mlGuYdZdP4tc9g.jpeg</url>
            <title>Stories by Aprajita on Medium</title>
            <link>https://medium.com/@stressed83?source=rss-68974d81f333------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:58:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stressed83/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[Building a Chat Component with OpenAI API, Predefined Queries, and Voice Input in React]]></title>
            <link>https://medium.com/@stressed83/building-a-chat-component-with-openai-api-predefined-queries-and-voice-input-in-react-fd0937f51a4e?source=rss-68974d81f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd0937f51a4e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Aprajita]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 10:26:31 GMT</pubDate>
            <atom:updated>2024-10-24T10:30:23.389Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Making Bots a Laughing Matter!”</h3><p>Who doesn’t love a good chatbot? Especially one that feels like it could take over your job someday (just kidding… or am I?). But seriously, creating a smart, responsive, and voice-enabled chatbot is easier than you think! In this tutorial, we’re going to build a <strong>React Chat Component</strong> that integrates with OpenAI’s API, provides <strong>predefined queries</strong> like ChatGPT, and even has voice input functionality because typing is <em>so</em> 2023.</p><h3>Prerequisites:</h3><ul><li>Basic knowledge of <strong>React</strong> and <strong>JavaScript</strong> (or an impressive ability to wing it).</li><li>Familiarity with <strong>Material-UI</strong> for those sweet, sweet UI components.</li><li><strong>OpenAI API Key</strong> — we’re building a smart chatbot, not a random button-clicker!</li></ul><h3>Step 1: Setting Up Your Project (AKA The “Hello World” of Chatbots)</h3><p>First, let’s set up a new React project, which is just a fancy way of saying “let’s clone another boilerplate”:</p><pre>npx create-react-app chat-component<br>cd chat-component</pre><p>Once we’ve ensured our directory is as pristine as a new pair of sneakers, let’s throw in some dependencies because we’re not barbarians.</p><pre>npm install @mui/material @emotion/react @emotion/styled axios react-toastify</pre><p>These tools will make our chat component look slick while providing functionality — plus, “toastify” just sounds delicious.</p><h3>Step 2: The Skeleton of a Chat Component (No Bones About It)</h3><p>Now that we’ve got everything installed, let’s create the most <em>barebones</em> chat component ever, just enough to convince people we’re actually doing something.</p><p>Create a ChatComponent.js file under the src/components/ folder:</p><pre>import React, { useState, useEffect, useRef } from &#39;react&#39;;<br>import { Avatar, TextField, Card, CardContent, Typography, Stack, styled, IconButton, InputAdornment, CircularProgress, Button } from &#39;@mui/material&#39;;<br>import MicIcon from &#39;@mui/icons-material/Mic&#39;;<br>import SendIcon from &#39;@mui/icons-material/Send&#39;;<br>import { toast } from &#39;react-toastify&#39;;<br>import axios from &#39;axios&#39;;</pre><h3>Step 3: Adding Some Style, Because We’re Fancy Like That</h3><p>A chatbot without style is like a taco without salsa — <em>bland</em>. So, we’ll use <strong>Material-UI’s styled components</strong> to make it pop. Fancy avatars? Check. Smooth animations? You bet!</p><pre>const BotAvatar = styled(Avatar)(({ theme }) =&gt; ({<br>  backgroundColor: theme.palette.secondary.main,<br>  marginRight: theme.spacing(4),<br>  height: &#39;60px&#39;,<br>  width: &#39;60px&#39;,<br>}));<br>const UserAvatar = styled(Avatar)(({ theme }) =&gt; ({<br>  backgroundColor: theme.palette.primary.main,<br>  marginLeft: theme.spacing(0),<br>  height: &#39;60px&#39;,<br>  width: &#39;60px&#39;,<br>}));<br>const FancyLoader = styled(CircularProgress)(({ theme }) =&gt; ({<br>  animation: `spin 2s linear infinite`,<br>  color: theme.palette.primary.main,<br>}));<br>const animation = &#39;@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }&#39;;<br>const AnimatedCard = styled(Card)(({ theme }) =&gt; ({<br>  animation: `${animation} 0.5s ease-out`,<br>  marginBottom: theme.spacing(2),<br>  maxWidth: &#39;70%&#39;,<br>}));</pre><h3>Step 4: State Management Like a Pro (But Really, It’s Just useState)</h3><p>Let’s bring our component to life with <strong>state management</strong>. We’re talking message handling, user input, and OpenAI responses — essentially all the fun parts without the existential crisis of AI taking over.</p><pre>function ChatComponent() {<br>  const [input, setInput] = useState(&#39;&#39;);<br>  const [messages, setMessages] = useState([]);<br>  const messagesEndRef = useRef(null);<br>const handleInputChange = (e) =&gt; {<br>    setInput(e.target.value);<br>  };<br>  const handleSendMessage = async () =&gt; {<br>    if (!input.trim()) return;<br>    setMessages([...messages, { role: &#39;user&#39;, content: input }]);<br>    try {<br>      const response = await axios.post(&#39;/openai-api-url&#39;, { prompt: input });<br>      setMessages([...messages, { role: &#39;user&#39;, content: input }, { role: &#39;assistant&#39;, content: response.data }]);<br>    } catch (error) {<br>      toast.error(&#39;OpenAI has ghosted us&#39;);<br>    }<br>    setInput(&#39;&#39;);<br>  };<br>}</pre><h3>Step 5: Predefined Queries Like a Pro (Because Typing Is Overrated)</h3><p>Now for the magic — let’s add <strong>predefined queries</strong> like ChatGPT, where users can <em>click</em> instead of <em>think</em>. These queries will let users jump straight into action, check the weather, or ask the meaning of life (there isn’t any, by the way).</p><pre>const startStaticConversation = () =&gt; {<br>  setMessages([<br>    {<br>      role: &#39;assistant&#39;,<br>      content: &#39;How can I help you today?&#39;,<br>      predefinedQueries: [<br>        &#39;Tell me a joke?&#39;,<br>        &#39;Am I a joke?&#39;,<br>        &#39;Roast me based upon my last few prompts&#39;,<br>      ],<br>    },<br>  ]);<br>};</pre><p>And for the “Wow, this is so easy!” part, let’s make these queries clickable buttons:</p><pre>const renderPredefinedQueries = (queries) =&gt; {<br>  return queries.map((query, index) =&gt; (<br>    &lt;Button<br>      key={index}<br>      variant=&quot;contained&quot;<br>      color=&quot;primary&quot;<br>      onClick={() =&gt; handleSendMessage(query)}<br>      style={{ marginRight: &#39;10px&#39;, marginTop: &#39;10px&#39; }}<br>    &gt;<br>      {query}<br>    &lt;/Button&gt;<br>  ));<br>};</pre><h3>Step 6: Voice Input — Because Who Types Anymore?</h3><p>Typing? In this economy? Let’s add <strong>voice input</strong> using the <strong>SpeechRecognition API</strong> because we’re all about cutting-edge features (and being lazy).</p><pre>const startListening = () =&gt; {<br>  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;<br>  const recognition = new SpeechRecognition();<br>recognition.start();<br>  recognition.onresult = (event) =&gt; {<br>    const transcript = event.results[0][0].transcript;<br>    handleSendMessage(transcript);<br>  };<br>  recognition.onstart = () =&gt; setIsListening(true);<br>  recognition.onend = () =&gt; setIsListening(false);<br>};<br>return (<br>  &lt;IconButton onClick={startListening}&gt;<br>    {isListening ? &lt;MicIcon /&gt; : &lt;MicIcon /&gt;}<br>  &lt;/IconButton&gt;<br>);</pre><h3>Step 7: Putting It All Together (Like a Tech Sandwich)</h3><p>Here comes the fun part — throwing everything together into a slick, responsive chat interface. Yes, that means voice input, predefined queries, smooth animations, and an OpenAI-powered assistant that will <em>definitely</em> not take over the world.</p><pre>return (<br>  &lt;Card style={{ padding: &#39;20px&#39;, width: &#39;100%&#39;, overflowX: &#39;hidden&#39; }}&gt;<br>    &lt;div style={{ height: &#39;66vh&#39;, overflowY: &#39;auto&#39; }}&gt;<br>      &lt;Stack spacing={2}&gt;<br>        {messages.map((message, index) =&gt; (<br>          &lt;AnimatedCard key={index}&gt;<br>            &lt;CardContent&gt;<br>              &lt;Typography variant=&quot;body2&quot; color=&quot;inherit&quot;&gt;<br>                {message.content}<br>              &lt;/Typography&gt;<br>              {message.predefinedQueries &amp;&amp; renderPredefinedQueries(message.predefinedQueries)}<br>            &lt;/CardContent&gt;<br>          &lt;/AnimatedCard&gt;<br>        ))}<br>      &lt;/Stack&gt;<br>      &lt;div ref={messagesEndRef} /&gt;<br>    &lt;/div&gt;&lt;TextField<br>      value={input}<br>      onChange={handleInputChange}<br>      placeholder=&quot;Type a message...&quot;<br>      fullWidth<br>      InputProps={{<br>        startAdornment: (<br>          &lt;InputAdornment position=&quot;start&quot;&gt;<br>            &lt;IconButton onClick={startListening}&gt;&lt;MicIcon /&gt;&lt;/IconButton&gt;<br>          &lt;/InputAdornment&gt;<br>        ),<br>        endAdornment: (<br>          &lt;InputAdornment position=&quot;end&quot;&gt;<br>            &lt;IconButton onClick={handleSendMessage} disabled={!input.trim()}&gt;<br>              &lt;SendIcon /&gt;<br>            &lt;/IconButton&gt;<br>          &lt;/InputAdornment&gt;<br>        ),<br>      }}<br>    /&gt;<br>  &lt;/Card&gt;<br>);<br></pre><h3>Step 8: Testing and Wrapping It Up</h3><p>Congratulations! You’ve just built a conversational UI that’s smart, responsive, and — let’s be real — pretty fun to interact with. Whether it’s predefined queries, voice input, or fancy animations, this component shows how easy it is to put together a <strong>React-based chatbot</strong> that integrates with <strong>OpenAI’s API</strong>.</p><p>In the end, this is just another <strong>conversational UI</strong>. But, with the power of modern web development frameworks like React and the versatility of OpenAI, building intelligent chat components can be done <strong>quickly</strong> and <strong>efficiently</strong>. You can easily customize this component further, whether you’re adding more predefined queries, tweaking the styling, or even scaling it up for more complex conversational flows.</p><p>The best part? You can create a smart and polished chatbot interface like this in no time, leaving you with plenty of time to sit back and have a conversation… with your very own bot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd0937f51a4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Miller’s Columns vs. Tree Structures: A Showdown of Hierarchical Navigation ️]]></title>
            <link>https://medium.com/@stressed83/millers-columns-vs-tree-structures-a-showdown-of-hierarchical-navigation-%EF%B8%8F-19bc3f2f9a34?source=rss-68974d81f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/19bc3f2f9a34</guid>
            <category><![CDATA[usability]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[ui-scalability]]></category>
            <category><![CDATA[millerscolumn]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Aprajita]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 05:45:59 GMT</pubDate>
            <atom:updated>2024-10-03T17:42:37.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8mGWCDkqE6ZXIDPRoLavw.png" /></figure><p>So, you’re knee-deep in hierarchical data, and you need a way to display it. Should you go for the sleek, column-by-column approach of Miller’s Columns, or embrace the branching chaos of the Tree Structure? Let’s break it down with a touch of humor, real-world examples, UX laws, and a splash of imagery.</p><h3>1. Miller’s Columns: The Linear Explorer 🗂️</h3><p>If you are not very familiar with Miller’s Columns have a quick browse to <a href="https://en.wikipedia.org/wiki/Miller_columns">https://en.wikipedia.org/wiki/Miller_columns</a></p><p>Miller’s Columns are like that super-organized friend who insists on doing things one step at a time. Imagine an explorer navigating a series of islands: they’ll only move to the next island after thoroughly examining the one they’re on.</p><h4>Where You’ve Seen It:</h4><ul><li><strong>Mac’s Finder (Column View):</strong> If you’ve ever used a Mac, you’ve probably encountered Miller’s Columns in the Finder app’s “Column View.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*ltICo8E3O5aj0JKM30rtMQ.png" /></figure><ul><li><strong>Linux File Managers:</strong> Many Linux file managers, like <strong>Nemo</strong> and <strong>Pantheon Files</strong>, have a column view option.</li><li><strong>Online Stores (Amazon, eBay):</strong> Category navigation, such as “Electronics &gt; Laptops &gt; Gaming.”</li></ul><h4>Pros:</h4><ul><li><strong>Linear Focus:</strong> Shows you the way, one column at a time, perfect for deep hierarchies.</li><li><strong>Reduced Clutter:</strong> Reveals only the current path, reducing visual noise.</li><li><strong>Performance Boost:</strong> Uses lazy loading, which keeps the interface smooth for large datasets.</li></ul><h4>UX Laws at Play:</h4><ul><li><strong>Hick’s Law:</strong> By presenting only one level at a time, Miller’s Columns reduce the number of choices a user must consider, thus speeding up decision-making. This aligns perfectly with <strong>Hick’s Law</strong>, which states that the more options you present, the longer it takes for someone to make a decision. By limiting visible options, it simplifies user interaction.</li><li><strong>Miller’s Law (No Relation!):</strong> The original <strong>Miller’s Law</strong> states that the average person can only keep about 7 (plus or minus 2) items in their working memory. Miller’s Columns are great at respecting this limitation, focusing on a manageable subset of the hierarchy at each level.</li></ul><h4>Companies That Use It:</h4><ul><li><strong>Apple:</strong> Mac Finder’s column view is a prime example.</li><li><strong>Slack:</strong> The sidebar navigation follows a similar column-based approach.</li></ul><h3>2. Tree Structures: The Trailblazing Hiker 🌲</h3><p>Tree structures are like that adventurous hiker who loves exploring every nook and cranny of the forest. They show you the whole forest (hierarchy) and all the possible trails (branches) right away.</p><h4>Where You’ve Seen It:</h4><ul><li><strong>Windows File Explorer:</strong> Provides a classic tree structure for navigating folders.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*UiNCOoo1OGanBZStb7OWEQ.png" /></figure><ul><li><strong>Linux File Managers (Tree View):</strong> File managers like <strong>Nautilus</strong> offer a tree view option.</li><li><strong>Web Development (APIs, Navigation):</strong> IDEs like <strong>VS Code</strong> use a tree structure to display folder directories.</li></ul><h4>Pros:</h4><ul><li><strong>Full Overview:</strong> Shows the entire structure, useful for comparing multiple branches.</li><li><strong>Flexible Navigation:</strong> Expand multiple branches for side-by-side comparison.</li><li><strong>Compact Usage of Space:</strong> Grows vertically, efficiently using screen height.</li></ul><h4>UX Laws at Play:</h4><ul><li><strong>Fitts’ Law:</strong> Tree structures can become visually cluttered, so it’s crucial to consider <strong>Fitts’ Law</strong>, which states that the time to acquire a target is a function of the distance and size of the target. Expanding and collapsing nodes need to be designed for easy interaction to avoid making users hunt for tiny icons.</li><li><strong>Aesthetic-Usability Effect:</strong> Trees can look complex, which might discourage interaction. However, a well-designed tree with clear visual cues (e.g., icons, spacing) aligns with the <strong>Aesthetic-Usability Effect</strong> — users perceive more aesthetically pleasing designs as easier to use. Thus, proper design can make a complex tree structure feel approachable.</li></ul><h4>Companies That Use It:</h4><ul><li><strong>Microsoft:</strong> Windows File Explorer uses the tree structure for navigating directories.</li><li><strong>JetBrains:</strong> IDEs like <strong>IntelliJ IDEA</strong> and <strong>WebStorm</strong> use a tree-based view for files and project structures.</li><li><strong>Atlassian (Jira):</strong> Uses tree structures to display nested tasks and epics.</li></ul><h3>3. Which One’s Better for Scalability?</h3><h4>Miller’s Columns:</h4><ul><li><strong>Ideal for Deep Hierarchies:</strong> Uses <strong>Hick’s Law</strong> to reduce choices, making it easier to scale deep structures.</li><li><strong>Lazy Loading Love:</strong> Simplifies the UI by only showing what’s necessary at each step, enhancing performance.</li></ul><h4>Tree Structures:</h4><ul><li><strong>Perfect for Broad Overviews:</strong> Uses <strong>Fitts’ Law</strong> by optimizing the interface for easy interaction with nodes, great for showing broad hierarchies with multiple branches.</li><li><strong>Virtualization Required:</strong> Requires careful application of <strong>Miller’s Law</strong> to prevent overwhelming the user with too many open branches at once.</li></ul><h3>4. Passing Data and Handling Events: Making Them Talk!</h3><h4>In Miller’s Columns (Like Mac Finder):</h4><ul><li><strong>Data Passing:</strong> Attributes represent the current path, using <strong>Hick’s Law</strong> to minimize choices.</li><li><strong>Event Handling:</strong> Click events trigger the next column’s data loading, maintaining focus on a linear path.</li></ul><h4>In Tree Structures (Like Windows Explorer):</h4><ul><li><strong>Data Passing:</strong> Nodes carry data in attributes, supporting complex interaction.</li><li><strong>Event Handling:</strong> Expanding and collapsing branches require careful design in line with <strong>Fitts’ Law</strong> for easy navigation.</li></ul><h3>5. So, Who Wins? 🏆</h3><ul><li><strong>Miller’s Columns:</strong> Best for sequential navigation and deep hierarchies. Aligns with <strong>Hick’s Law</strong> to make navigation feel manageable and intuitive.</li><li><strong>Tree Structures:</strong> Perfect for broad overviews and flexible navigation, with <strong>Fitts’ Law</strong> and the <strong>Aesthetic-Usability Effect</strong> guiding a user-friendly design.</li></ul><h3>Final Thoughts</h3><p>So, what’s it going to be? The structured, linear journey of Miller’s Columns, or the expansive exploration of a Tree Structure? By applying UX laws, we can choose the design that not only fits the data but also provides a seamless user experience.</p><p><strong>Remember:</strong> It’s not about choosing the fanciest method; it’s about using <strong>Hick’s Law</strong>, <strong>Fitts’ Law</strong>, and <strong>Miller’s Law</strong> to make your data easy to navigate and understand. Now, go create an experience your users will love! 🌳🗂️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19bc3f2f9a34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating React Components into GWT: Making Modern and Legacy Frameworks Play Nice (With a Twist…]]></title>
            <link>https://javascript.plainenglish.io/integrating-react-components-into-gwt-making-modern-and-legacy-frameworks-play-nice-with-a-twist-c07c4ea058be?source=rss-68974d81f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/c07c4ea058be</guid>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[legacy-systems]]></category>
            <category><![CDATA[gwt]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Aprajita]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 11:13:08 GMT</pubDate>
            <atom:updated>2024-10-07T03:38:38.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kq7RnWiEfbXnky0MALx0Q.png" /></figure><h3>Integrating React Components into GWT: Making Modern and Legacy Frameworks Play Nice (With a Twist of Nerd Humor!)</h3><h3>Problem Statement</h3><p>So, you’ve got this cool, shiny new React component, and it’s sitting there saying, “Hey, put me in the game!” But you’re stuck working with a legacy GWT (Google Web Toolkit) application that acts more like a grandparent, grumbling about how things used to be. Can the two worlds ever collide peacefully? Yes, they can! And that’s what we’re diving into here — how to make your React components show up in your GWT app like it’s no big deal. Plus, I’ll throw in some jokes to make this journey a bit more fun.</p><h3>The Grand Plan</h3><p>We want to:</p><ol><li>Create React components.</li><li>Turn them into <strong>web components</strong>.</li><li>Inject them into GWT using the power of <strong>ScriptInjector</strong> and control them using <strong>JSInterop</strong>.</li><li>Publish these web components to an <strong>artifactory</strong> (you know, to keep things nice and organized).</li></ol><p>Sounds simple enough, right? Now, let’s roll up our sleeves and do it the right way.</p><h3>Creating Web Components: Two Paths to Greatness</h3><p>First things first, let’s get our React components wrapped up as web components. We’ve got two main ways to do this:</p><h3>1. Option 1: Using Custom Element API (DIY Web Components)</h3><p>Ah, the good old manual way. Think of this like cooking a fancy dish from scratch instead of microwaving something from the freezer. You get to customize everything, but it requires a bit more effort.</p><h4>Step 1: Create Your React Component</h4><p>Here’s a simple React component we want to use in our legacy GWT app:</p><pre>// MyReactComponent.js<br>import React from &#39;react&#39;;<br>const MyReactComponent = ({ title, onButtonClick }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{title}&lt;/h2&gt;<br>      &lt;button onClick={() =&gt; onButtonClick(&#39;React says hi!&#39;)}&gt;Click Me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default MyReactComponent;</pre><h4>Step 2: Wrap It in a Custom Web Component</h4><p>This is where we turn it into a web component using the Custom Element API:</p><pre>// MyReactComponentWrapper.js<br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import MyReactComponent from &#39;./MyReactComponent&#39;;<br>class MyReactWebComponent extends HTMLElement {<br>  constructor() {<br>    super();<br>    this.mountPoint = document.createElement(&#39;div&#39;);<br>    this.attachShadow({ mode: &#39;open&#39; }).appendChild(this.mountPoint);<br>  }connectedCallback() {<br>    this.render();<br>  }<br>  static get observedAttributes() {<br>    return [&#39;title&#39;];<br>  }<br>  attributeChangedCallback(name, oldValue, newValue) {<br>    this.render();<br>  }<br>  render() {<br>    ReactDOM.render(<br>      &lt;MyReactComponent <br>        title={this.getAttribute(&#39;title&#39;)} <br>        onButtonClick={(message) =&gt; this.dispatchEvent(new CustomEvent(&#39;button-clicked&#39;, { detail: message }))}<br>      /&gt;,<br>      this.mountPoint<br>    );<br>  }<br>}<br>customElements.define(&#39;my-react-web-component&#39;, MyReactWebComponent);</pre><p>Here’s what’s happening:</p><ul><li><strong>Data Passing:</strong> We pass data using HTML attributes (title).</li><li><strong>Event Handling:</strong> When the button is clicked, the web component dispatches a custom event (button-clicked) that the host application (GWT in this case) can listen to.</li></ul><h3>2. Option 2: Use react-to-web-component (Microwave Magic)</h3><p>If you’re like me and sometimes just want to get things done quickly, use the react-to-web-component library to wrap your React component as a web component. It&#39;s like taking the express lane at the grocery store!</p><h4>Step 1: Install react-to-web-component</h4><pre>npm install react-to-web-component</pre><h4>Step 2: Wrap Your Component</h4><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import reactToWebComponent from &#39;react-to-web-component&#39;;<br>import MyReactComponent from &#39;./MyReactComponent&#39;;<br>// Wrap it up!<br>const MyReactWebComponent = reactToWebComponent(MyReactComponent, React, ReactDOM);<br>// Register the custom element<br>customElements.define(&#39;my-react-web-component&#39;, MyReactWebComponent);</pre><p>With just a few lines, your React component is now a web component. This library also supports data passing and event handling in a pretty straightforward manner.</p><h4>Passing Data and Handling Events:</h4><pre>&lt;my-react-web-component title=&quot;Hello from React!&quot;&gt;&lt;/my-react-web-component&gt;</pre><p>In the React component, you can pass data as properties and handle events using standard methods.</p><h3>3. Bundling and Publishing to Artifactory (Time to Share the Goods)</h3><p>Now, let’s bundle this up using Webpack and publish it to an artifactory. (Because sharing is caring, right?)</p><h4>Step 1: Bundle the Component Using Webpack</h4><pre>// webpack.config.js<br>const path = require(&#39;path&#39;);<br>module.exports = {<br>  entry: &#39;./src/MyReactComponentWrapper.js&#39;, // or the &#39;react-to-web-component&#39; version<br>  output: {<br>    path: path.resolve(__dirname, &#39;dist&#39;),<br>    filename: &#39;my-react-web-component.js&#39;,<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.(js|jsx)$/,<br>        exclude: /node_modules/,<br>        use: {<br>          loader: &#39;babel-loader&#39;,<br>          options: {<br>            presets: [&#39;@babel/preset-react&#39;],<br>          },<br>        },<br>      },<br>    ],<br>  },<br>};</pre><pre>npx webpack --config webpack.config.js</pre><h4>Step 2: Publish to Artifactory</h4><ol><li>Create a .npmrc file and configure the artifactory URL</li><li>Login to your artifactory</li><li>Publish the component</li></ol><pre>registry=&lt;YOUR_ARTIFACTORY_URL&gt;/artifactory/api/npm/&lt;REPOSITORY_NAME&gt;/</pre><pre>npm login --registry=&lt;YOUR_ARTIFACTORY_URL&gt;/artifactory/api/npm/&lt;REPOSITORY_NAME&gt;/</pre><pre>npm publish</pre><h3>4. Integrating into GWT Using ScriptInjector and JSInterop</h3><p>Now comes the moment of truth. How do we convince GWT to embrace this modern web component?</p><h4>Step 1: Use ScriptInjector to Load the Web Component</h4><pre>import com.google.gwt.core.client.ScriptInjector;<br>public class WebComponentLoader {<br>    public static void injectWebComponentScript() {<br>        ScriptInjector.fromUrl(&quot;https://your-artifactory-url/path/to/my-react-web-component.js&quot;)<br>            .setCallback(new Callback&lt;Void, Exception&gt;() {<br>                @Override<br>                public void onFailure(Exception reason) {<br>                    // It broke... handle the sadness<br>                }<br>                @Override<br>                public void onSuccess(Void result) {<br>                    // Hooray! Component loaded!<br>                }<br>            }).inject();<br>    }<br>}</pre><h4>Step 2: Use JSInterop to Interact with the Web Component</h4><pre>import jsinterop.annotations.JsType;<br>import jsinterop.annotations.JsProperty;<br>import jsinterop.annotations.JsPackage;<br>@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = &quot;HTMLElement&quot;)<br>public class MyReactWebComponent {<br>    @JsProperty<br>    public native void setTitle(String title);<br>    @JsProperty<br>    public native String getTitle();<br>}</pre><h4>Step 3: Handle Events in GWT</h4><p>Add a listener for the custom event:</p><pre>public void addReactWebComponent() {<br>    MyReactWebComponent reactComponent = (MyReactWebComponent) DomGlobal.document.createElement(&quot;my-react-web-component&quot;);<br>    <br>    // Listen for the custom event<br>    reactComponent.addEventListener(&quot;button-clicked&quot;, event -&gt; {<br>        JsPropertyMap&lt;Object&gt; detail = (JsPropertyMap&lt;Object&gt;) event.detail;<br>        DomGlobal.console.log(&quot;Received event: &quot; + detail.get(&quot;detail&quot;));<br>    });<br>    <br>    // Set properties<br>    reactComponent.setTitle(&quot;Hello from GWT!&quot;);<br>    <br>    // Append to the GWT RootPanel<br>    RootPanel.get().getElement().appendChild((HTMLElement) reactComponent);<br>}</pre><h3>Wrapping Up</h3><p>And there you have it! Your React components are now GWT-friendly, and you have two ways to make it happen — either roll up your sleeves with the Custom Element API or take the express route with react-to-web-component. We also covered how to pass data, handle events, and publish the components to an artifactory.</p><p>It may seem like a lot, but hey, sometimes you have to do a bit of heavy lifting to bring the past and future together. Now, go forth and make those legacy apps shine with your modern React components! 🎉</p><p>If you have any questions, feel free to leave them in the comments below. I promise to respond… eventually. 😅</p><p>Special note to the developer from my team, who did this POC but was too busy to publish on Medium. Yes <a href="https://medium.com/u/1f7d276c3543">Jayant Panwar</a>, I am talking to you. 😐</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c07c4ea058be" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/integrating-react-components-into-gwt-making-modern-and-legacy-frameworks-play-nice-with-a-twist-c07c4ea058be">Integrating React Components into GWT: Making Modern and Legacy Frameworks Play Nice (With a Twist…</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating React with Google Web toolkit (GWT)]]></title>
            <link>https://medium.com/@stressed83/integrating-react-with-google-web-toolkit-gwt-8b6c0fb0e77b?source=rss-68974d81f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b6c0fb0e77b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[gwt]]></category>
            <category><![CDATA[integration]]></category>
            <dc:creator><![CDATA[Aprajita]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 03:50:31 GMT</pubDate>
            <atom:updated>2021-10-21T03:50:31.553Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Before you wonder “Isn’t GWT dead in 2021?” Let me answer, no it is not dead. It has survived and is still relevant. The latest release was published in May,2020 and it has pretty much survived <a href="https://killedbygoogle.com/">Killed by Google</a> scythe. Much to JavaScript developer pleasure it has been also in path to be able to integrate and coexist with modern JavaScript libraries.</blockquote><p>The aspiration behind this write-up is the fact that there are still many huge legacy applications which have been developed using GWT. And there comes a situation when you want to use a modern library like React in these existing applications.</p><blockquote>To be noted, I will consider both JSNI and <a href="http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJsInterop.html">JsInterop</a> implementation. (JSNI has been removed from GWT 3 onward)</blockquote><blockquote>Also we are trying to find a way to integrate (not completely rewrite or replace) React into GWT.</blockquote><p>We would be using global functions defined on windows scope to integrate/communicate between GWT and React</p><p>Step 1: Creating React application</p><p><a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">create-react-app</a> would be the best place to start with for creating a simple new single-page application using react with basic configuration.</p><p>For rendering an element into the DOM, we usually have a “root” DOM node inside which everything will be managed by React DOM.</p><p>You will find a code snippet like this inside your index.js</p><blockquote><em>ReactDOM.render(&lt;App /&gt;, document.getElementById(“root”)); ​</em></blockquote><p>The “root” element would be defined inside index.html</p><p>In our case instead of attaching react element to the “root” defined inside index.html we would expect GWT to pass on the element inside which we would render react elements.</p><blockquote><em>export default function renderReactComponent(selectorFromGwt) {<br> ReactDOM.render(&lt;App /&gt;, document.getElementById(selectorFromGwt));<br>}<br>window.renderReactComponent = renderReactComponent;</em></blockquote><p>Step 2: Build react application</p><p>To be able to use the created react component, build the application. In our case app is created using <a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">create-react-app</a> so run following:</p><blockquote>npm run build</blockquote><p>It builds the app for production and publish inside the build folder.</p><p>Important note: Instead of using basic <a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">create-react-app</a> we can use any other boilerplate, based upon the technology selection of your react app. (We went for express+react+typescript+webpack)</p><p>Step 3: Include react resources inside GWT</p><p>GWT provide multiple ways to include an external JS resource. Few options are listed below:</p><blockquote>Using <a href="http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/client/ScriptInjector.html">ScriptInjector</a>.fromUrl()</blockquote><blockquote>Using JsniBundle</blockquote><blockquote>Placing script tag directly inside your index.html</blockquote><p>In our case we used <a href="http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/client/ScriptInjector.html">ScriptInjector</a>.fromUrl() to load the JS bundle and CSS file generated by step 2.</p><p>Step 4: Creating a panel in GWT to render react component</p><p>Inside your GWT code you can create a panel which could be used to render react component as below (both JSNI and JSInterop ways are defined, choose either based upon version of GWT):</p><blockquote>public class PanelForReactComponent extends Composite {<br> private static Binder uiBinder = GWT.create(Binder.class);</blockquote><blockquote>interface Binder extends UiBinder&lt;Widget, PanelForReactComponent&gt; {<br> }</blockquote><blockquote><a href="http://twitter.com/UiField">@UiField</a><br> ScrollPanel content;</blockquote><blockquote>public PanelForReactComponent() {<br> initWidget(uiBinder.createAndBindUi(this));<br> content.getElement().setId(“root_for_react_component”);<br> }</blockquote><blockquote><a href="http://twitter.com/Override">@Override</a><br> protected void onLoad() {<br> super.onLoad();</blockquote><blockquote>//use either JSNI or JSInterop as shown below<br> renderReactComponent_JSNI(“root_for_react_component”);<br> renderReactComponent(“root_for_react_component”);<br> }<br> <br> private native void renderReactComponent_JSNI(String root)/*-{<br> (function(root) {<br> $wnd.renderReactComponent(root);<br> })(root);<br> }-*/;</blockquote><blockquote><a href="http://twitter.com/JsMethod">@JsMethod</a>(namespace = JsPackage.GLOBAL) // this translates to JS method defined in window namespace<br> public static native void renderComponent(String panelId);<br>}</blockquote><p>To enable communication between React and GWT, we can create functions with windows scope at both end.</p><p>Step 5:</p><p>At GWT side:</p><blockquote>//Using JSInterop</blockquote><blockquote><a href="http://twitter.com/JsType">@JsType</a>(namespace = JsPackage.GLOBAL, name = “ReactGwtInterface”)<br>public class ReactGwtInterface {</blockquote><blockquote>/**<br> * To be called as window.ReactGwtInterface.fromReactToGWT(parameters); <br> */<br> <a href="http://twitter.com/JsMethod">@JsMethod</a><br> public static void fromReactToGWT() {<br> }</blockquote><blockquote>/**<br> * Method defined inside react <br> */<br> <a href="http://twitter.com/JsMethod">@JsMethod</a>(namespace = JsPackage.GLOBAL)<br> public static native void fromGWTToReact();</blockquote><blockquote>}</blockquote><blockquote>//Using JSNI define a method to add/call functions defined in windows scope</blockquote><blockquote>private native void bootstrapReactComponent(String root)/*-{<br> (function(root) {<br> $wnd.fromReactToGWT = function(data) {<br> console.log(data);<br> };<br> $wnd.fromGWTToReact();<br> })(root);<br> }-*/;</blockquote><p>At React side:</p><blockquote>export function fromGWTToReact() {<br> }</blockquote><blockquote>window.fromGWTToReact = fromGWTToReact;</blockquote><p>This is the simplest way we can integrate a React component into existing GWT application. While defining architecture it is important to maintain clear interfaces at both side. It is advisable to use JSInterop as it provide annotation based structure, but if that is not possible(in legacy application use JSNI).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b6c0fb0e77b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I don’t want to be friends with computers; I don’t want it to tell me jokes]]></title>
            <link>https://uxdesign.cc/i-dont-want-to-be-friends-with-computers-i-don-t-want-it-to-tell-me-jokes-duh-689a61919a6?source=rss-68974d81f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/689a61919a6</guid>
            <category><![CDATA[usability]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[t]]></category>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Aprajita]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 04:24:30 GMT</pubDate>
            <atom:updated>2019-09-29T16:32:17.888Z</atom:updated>
            <content:encoded><![CDATA[<h4>Humor in UX — UX designers spend their lives trying to convince everyone that you need to develop empathy with your users. You have to factor in the “human” part of the interactions.</h4><p>Even a drab work like simply filling a login form can be made interesting. UX folks want you to engage the user. Humor is a simple tool through which you can make anything interesting, engaging and “human”.</p><blockquote>But !!!</blockquote><blockquote>I don’t want to be friends with computers. You can keep your silly jokes to yourself. I open an application to perform a set of work. I certainly do not want my banking application to send a “joke” notification like “Haha your account has zero balance. Gotcha !! Was just kidding !!!”</blockquote><p>Well there is a fine line between being an absolute jerk and make your user do this to you</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FzrdUjl6N99nLq%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FzrdUjl6N99nLq%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FzrdUjl6N99nLq%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="344" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ad2f82b0e438a1b2cbe537170bdf5a9/href">https://medium.com/media/0ad2f82b0e438a1b2cbe537170bdf5a9/href</a></iframe><p>Instead you can try some subtle humor to engage your audience (without risking being mauled by a giant panda)</p><ol><li><strong><em>We all have been proving ourselves to the computer that we are not a robot lately (I mean I need to prove myself to something that we human created that I am not a robot. Oh the humanity !)</em></strong></li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F10p3VEnw29dD44%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F10p3VEnw29dD44%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F10p3VEnw29dD44%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="115" frameborder="0" scrolling="no"><a href="https://medium.com/media/326c1b1db52dcd523a6665189ae5e917/href">https://medium.com/media/326c1b1db52dcd523a6665189ae5e917/href</a></iframe><p>Reinvent this captcha with something witty. Throwing an example here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*dMZ4GIz_Pgv4HY2zGsSaYg.png" /></figure><p><em>But wait choose your question wisely. You might get mauled by panda if you make fun of panda.</em></p><p><strong><em>2. When you fall down you laugh on yourself (everybody else is already laughing so better join them)</em></strong></p><p>How would you like to get an error like this while doing some important transaction :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*0uF3jzKl0WHaOJjlwMk78g.png" /><figcaption>This bring fear to heart of the bravest!!</figcaption></figure><p>Instead take a cue from applications like below and gracefully accept that something went wrong and provide an alternative to resume the work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*JdY224Wnw5BzbNie7p_nNQ.png" /></figure><p><strong><em>3. Remember the Microsoft word paperclip “clippy” we all wanted to murder. Try something like that but which makes you feel less murdery.</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o85xKrwKwGLLeYDao%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fstickers%2Fsupercompressor-transparent-3o85xKrwKwGLLeYDao&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o85xKrwKwGLLeYDao%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="522" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f4dcd8553b0c5a87403249995f9004/href">https://medium.com/media/88f4dcd8553b0c5a87403249995f9004/href</a></iframe><p>Try giving your user a freedom and authority of the kind of help they need and do not beat on the head with some information, instead allow them to ask for the help like a friendly little chatbot from React Simple Chatbot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*H8c1AHH0z1aO4eGgwc4Nsw.gif" /></figure><p><strong><em>4. Give brownies to user when they are able to do some task. We all want those golden foil stars. Don’t we ?</em></strong></p><p>At least acknowledge that the task has been successfully completed or provide predictability by showing what all need to be done to complete the task</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*gbj4zV1unp6Dus3WUTR7gQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*jJb5z23VtAzRfHMFIEJthg.png" /></figure><p>Be careful about the messages you display to user. BTW anybody remember when Windows XP thought this UX is a good idea? (No one remembers ? Damn am I <em>that</em> old :|)</p><p><strong><em>5. Engage Karen with some activity before she calls for your manager.</em></strong></p><p>Sometimes lags are real and your user end might end up in situation like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*Q0-3emEzj5Wbp-FiUfGZ3g.gif" /></figure><p>Be proactive and let the user know what is happening before the panda come looking for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SBR3OvSZQeY5QYJAbnVVwA.gif" /><figcaption>Keep fishing while we do our thing !</figcaption></figure><p>So here I summon all my fellow nerds to not to be afraid of tickling that funny bone of your non-nerd users and let them feel that the person sitting behind the computer is also human.</p><p>Good UX is not an afterthought, it is not an optional consideration either. With this I end my ranting.</p><p>Signing off.</p><p>Reluctant Designer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=689a61919a6" width="1" height="1" alt=""><hr><p><a href="https://uxdesign.cc/i-dont-want-to-be-friends-with-computers-i-don-t-want-it-to-tell-me-jokes-duh-689a61919a6">I don’t want to be friends with computers; I don’t want it to tell me jokes</a> was originally published in <a href="https://uxdesign.cc/">UX Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live Streaming Data Using Kafka, Node JS, WebSocket and Chart JS]]></title>
            <link>https://medium.com/@stressed83/live-streaming-data-using-kafka-node-js-websocket-and-chart-js-8750acad549c?source=rss-68974d81f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/8750acad549c</guid>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Aprajita]]></dc:creator>
            <pubDate>Fri, 20 Sep 2019 02:44:21 GMT</pubDate>
            <atom:updated>2019-09-20T04:49:53.808Z</atom:updated>
            <content:encoded><![CDATA[<p>Yeah well the title of the story pretty much define what we were trying to achieve. This was a small POC that we started as a stepping stone to handle a huge data coming from our client and provide a live streaming after performing some processing.</p><p>I wanted to share my experience and give a walk through to anyone who would want to create a simple Live streaming of data using Kafka, Node JS, WebSocket and Chart JS :)</p><p>The reason for writing down this story is not to define something which might sound quite obvious but to allow reader to be able to follow the steps and have a working example. I found articles related to this topic on google but hardly found a step to step instruction that i could follow. And being new to Kafka, Node JS it could be daunting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*C7gJ8T2s1HFG7xuyM9UrPA.png" /></figure><p>Follow the guide below and you should be able to have something like this up and running in minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EAuAfdqJFJFTimysW7gOTQ.gif" /></figure><ol><li>Start with the basic Kafka installation on your machine using <a href="https://kafka.apache.org/quickstart">https://kafka.apache.org/quickstart</a></li></ol><p>Use the steps mentioned here to set-up and start Kafka server, create a topic and then use the Kafka console producer to send messages to the topic.</p><p>That mean do as said from Step 1 to Step 3 as in the Kafka quick-start document. Further we will use Step 4 to send some messages.</p><p>I have created a topic say — test1 and have my producer ready as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*4YWkwI-Fjy3ovY2YS_Vbag.png" /></figure><p>2. For creating a consumer using Node JS, we will be using <a href="https://www.npmjs.com/package/kafka-node#consumer">https://www.npmjs.com/package/kafka-node#consumer</a> . The purpose is straightforward — read messages from the Kafka topic. Following is a small snippet of code to create a consumer for the topic test1 that we created earlier in step 1. The topic I created is available on localhost:9092, modify your code according to your settings. (Just keep reference of this code in mind, we will be using it further)</p><pre><em>var kafka = require(‘kafka-node’);<br>var Consumer = kafka.Consumer,<br> client = new kafka.KafkaClient(“localhost:9092”),<br> consumer = new Consumer(<br> client, [ { topic: ‘test1’, partition: 0 } ], { autoCommit: false });</em></pre><pre><em>consumer.on(‘message’, function (message) {<br> console.log(message);<br>});</em></pre><p>3. On the Node JS service side we will be creating an WebSocket API using <a href="https://www.npmjs.com/package/websocket">https://www.npmjs.com/package/websocket</a>, which will be returning back data to the client (browser). A simple example would be as following:</p><pre><em>var WebSocketServer = require(‘websocket’).server;<br>var http = require(‘http’);<br> <br>var server = http.createServer(function(request, response) {<br> console.log(‘ Request recieved : ‘ + request.url);<br> response.writeHead(404);<br> response.end();<br>});<br>server.listen(8080, function() {<br> console.log(‘Listening on port : 8080’);<br>});<br> <br>webSocketServer = new WebSocketServer({<br> httpServer: server,<br> autoAcceptConnections: false<br>});<br> <br>function iSOriginAllowed(origin) {<br> return true;<br>}<br> <br>webSocketServer.on(‘request’, function(request) {<br> if (!iSOriginAllowed(request.origin)) {<br> request.reject();<br> console.log(‘ Connection from : ‘ + request.origin + ‘ rejected.’);<br> return;<br> }<br> <br> var connection = request.accept(‘echo-protocol’, request.origin);<br> console.log(‘ Connection accepted : ‘ + request.origin);<br> connection.on(‘message’, function(message) {<br> if (message.type === ‘utf8’) {<br> console.log(‘Received Message: ‘ + message.utf8Data);<br> }<br> });<br> connection.on(‘close’, function(reasonCode, description) {<br> console.log(‘Connection ‘ + connection.remoteAddress + ‘ disconnected.’);<br> });<br>});</em></pre><p>Step 3 Continued :</p><p>The purpose is to combine the Kafka consumer and the WebSocket API to play together and return data coming from Kafka producer. So combining the above two steps will result in something like this, let’s call it consumer.js.</p><pre><em>var WebSocketServer = require(‘websocket’).server;<br>var http = require(‘http’);<br> <br></em><strong><em>var kafka = require(‘kafka-node’);<br>var Consumer = kafka.Consumer,<br> client = new kafka.KafkaClient(“localhost:9092”),<br> consumer = new Consumer(<br> client, [ { topic: ‘test1’, partition: 0 } ], { autoCommit: false });</em></strong><em><br> <br>var server = http.createServer(function(request, response) {<br> console.log(‘ Request recieved : ‘ + request.url);<br> response.writeHead(404);<br> response.end();<br>});<br>server.listen(8080, function() {<br> console.log(‘Listening on port : 8080’);<br>});<br> <br>webSocketServer = new WebSocketServer({<br> httpServer: server,<br> autoAcceptConnections: false<br>});<br> <br>function iSOriginAllowed(origin) {<br> return true;<br>}<br> <br>webSocketServer.on(‘request’, function(request) {<br> if (!iSOriginAllowed(request.origin)) {<br> request.reject();<br> console.log(‘ Connection from : ‘ + request.origin + ‘ rejected.’);<br> return;<br> }<br> <br> var connection = request.accept(‘echo-protocol’, request.origin);<br> console.log(‘ Connection accepted : ‘ + request.origin);<br> connection.on(‘message’, function(message) {<br> if (message.type === ‘utf8’) {<br> console.log(‘Received Message: ‘ + message.utf8Data);<br> }<br> });<br></em><strong><em> consumer.on(‘message’, function (message) {<br> console.log(message);<br> connection.sendUTF(message.value);<br> });</em></strong><em><br> connection.on(‘close’, function(reasonCode, description) {<br> console.log(‘Connection ‘ + connection.remoteAddress + ‘ disconnected.’);<br> });<br>});</em></pre><p>Use command- node consumer.js to keep everything up and running</p><p>4. At the web browser (our client) we would invoke the WebSocket API and display the data as using Chart JS.</p><p>Whip out a index.html that would just include a placeholder for the chart and some basic script references:</p><pre>&lt;html&gt;<br>&lt;head&gt;<br> &lt;script src=”<a href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js">https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js</a>&quot;&gt;&lt;/script&gt;<br> &lt;script src=”<a href="https://cdn.jsdelivr.net/npm/chart.js@2.8.0">https://cdn.jsdelivr.net/npm/chart.js@2.8.0</a>&quot;&gt;&lt;/script&gt;<br> &lt;script type=”text/javascript” src=”index.js”&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;canvas id=”myChart” width=”400&quot; height=”400&quot;&gt;&lt;/canvas&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>In the index.js we would create a basic line chart and invoke the WebSocket API as shown below:</p><pre>$(document).ready(function(){<br> var count = 10;<br> var data = {<br> labels : [“0”,”1&quot;,”2&quot;,”3&quot;,”4&quot;,”5&quot;, “6”, “7”, “8”, “9”],<br> datasets : [<br> {<br> fillColor : “rgba(220,220,220,0.5)”,<br> strokeColor : “rgba(220,220,220,1)”,<br> pointColor : “rgba(220,220,220,1)”,<br> pointStrokeColor : “#fff”,<br> data : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]<br> }<br> ]<br> }<br> var updateData = function(oldVal, newVal){<br> var labels = oldVal[“labels”];<br> var dataSetInitial = oldVal[“datasets”][0][“data”];<br> labels.shift();<br> count++;<br> labels.push(count.toString());<br> var newData = Math.floor(newVal);<br> dataSetInitial.push(newData);<br> dataSetInitial.shift();<br> };</pre><pre>var ctx = document.getElementById(“myChart”).getContext(“2d”);<br> var chart = new Chart(ctx);<br> chart.Line(data, {animation : false}); <br> <br> function webSocketInvoke() {<br> <br> if (“WebSocket” in window) {<br> console.log(“WebSocket is supported by your Browser!”);<br> var ws = new WebSocket(“ws://localhost:8080/”,”echo-protocol”);<br> <br> ws.onopen = function() {<br> console.log(“Connection created”);<br> };<br> <br> ws.onmessage = function (evt) { <br> var received_msg = evt.data;<br> updateData(data, evt.data);<br> chart.Line(data, {animation : false})<br> console.log(received_msg );<br> };<br> <br> ws.onclose = function() { <br> console.log(“Connection closed”); <br> };<br> } else {<br> alert(“WebSocket NOT supported by your Browser!”);<br> }<br> }<br> webSocketInvoke();<br>});</pre><p>Open the index.html on any browser, We are all ready to check the live streaming of data by sending messages using Kafka console producer. The data would be shown as a line graph which will keep on updating as the messages are send.</p><p>See no rocket science involved.</p><p>This is the most basic example and in the upcoming stories I will be doing refactoring and make a more robust system. Hope this current draft allow you to create a simple example and understand end to end flow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8750acad549c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>