<?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 Anup Bishnoi on Medium]]></title>
        <description><![CDATA[Stories by Anup Bishnoi on Medium]]></description>
        <link>https://medium.com/@asyncanup?source=rss-bec38e5c817d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dVS3TcJZ68lfg5nP.jpeg</url>
            <title>Stories by Anup Bishnoi on Medium</title>
            <link>https://medium.com/@asyncanup?source=rss-bec38e5c817d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:27:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asyncanup/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[Build an AR Drum Set that you play with Body Gestures]]></title>
            <link>https://asyncanup.medium.com/build-an-ar-drum-set-that-you-play-with-body-gestures-31b20c9398e9?source=rss-bec38e5c817d------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b20c9398e9</guid>
            <category><![CDATA[ar]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[arkit]]></category>
            <category><![CDATA[drums]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[Anup Bishnoi]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 06:58:31 GMT</pubDate>
            <atom:updated>2020-12-29T07:05:49.414Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s build an Augmented Reality Drum Set that lets you play drums with your full body without any musical instruments! What? Yes.</p><p>Stand in front of camera 👀, bang imaginary drums with your hands 🥁, drums play for real! 📻🎶</p><p>Here’s a video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4xIckVvjjMQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4xIckVvjjMQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4xIckVvjjMQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3401ac6e563dbb45c6a77adb7a5b5f02/href">https://medium.com/media/3401ac6e563dbb45c6a77adb7a5b5f02/href</a></iframe><h3>What’s really happening here?</h3><p>Here’s what’s really happening here:</p><ul><li>Stand in front of camera<br>1. App starts phone camera.<br>2. App starts looking for human body in frame.<br>3. Finds you in the camera frame, and starts capturing body pose at 60fps.</li><li>Bang imaginary drums with your hands<br>1. You move your hands around as if playing an imaginary drum set laid out around you in 3D space.<br>2. App continuously matches the location of your two fists against 3D boundaries defined in code.</li><li>Drums play for real<br>1. App identifies when tracked fists enter pre-allocated areas in 3D space.<br>2. App plays the sound for drum instruments assigned to those areas.</li></ul><blockquote>Beyond just playing back the intended beat immediately, you can also see in the video that, in Recording mode, the app records the beats you hit, and replays them on a fixed tempo.</blockquote><h3>How does the body tracking work?</h3><p>This demo uses <a href="https://developer.apple.com/videos/play/wwdc2019/607">iOS ARKit’s Body Tracking</a> feature to track a human body in frame.</p><p>That information could come from your own on-device Machine Learning model, <a href="https://blog.tensorflow.org/2019/11/updated-bodypix-2.html">Tensorflow BodyPix</a>, <a href="https://www.tensorflow.org/lite/models/pose_estimation/overview">PoseNet</a>, or any other deep neural net.</p><p><strong>Here’s how to access body pose tracking data in ARKit</strong></p><p>Assuming you have an ARView already setup (follow any ARKit Getting Started tutorial online):</p><pre>class ViewController: UIViewController {<br> <a href="http://twitter.com/IBOutlet">@IBOutlet</a> var arView: ARView!<br>}</pre><p>Create a new ARSession with body pose tracking enabled (at any point after app startup, maybe in viewDidLoad()):</p><pre>arView.session.delegate = self<br>let configuration = ARBodyTrackingConfiguration()<br>arView.session.run(configuration)</pre><p>You also want to add a new AnchorEntity to the ARView scene:</p><pre>let characterAnchor = AnchorEntity()<br>arView.scene.addAnchor(characterAnchor)</pre><p>Then just add the session delegate method for arView.session to get a callback every frame with body pose data as seen by the back camera:</p><pre>extension ViewController: ARSessionDelegate {<br>    func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {<br>        if let bodyAnchor = anchors.first as? ARBodyAnchor,<br>            let rightHandTransform = bodyAnchor.skeleton.modelTransform(for: .rightHand),<br>            let leftHandTransform = bodyAnchor.skeleton.modelTransform(for: .leftHand) {<br>            let leftHand = leftHandTransform.columns.3<br>            let rightHand = rightHandTransform.columns.3<br>            update(leftHandAt:  (leftHand.x, leftHand.y),<br>                   rightHandAt: (rightHand.x, rightHand.y))<br>        }<br>    }<br>}</pre><blockquote>Note: We only need left and right hand locations for playing drums, so only need to extract the 3D locations of those two joints above. Also, transform.columns.3 gives us the 3rd column from the transform matrix, which is the position vector of the transform in 3D space.</blockquote><p>The leftHand, rightHand positions sent to update in the code above hold x and y values relative to the tracked person’s hip join. Which means bodyAnchor.skeleton.modelTransform(for:) for hip joint returns (0, 0, 0) as the 3D position.</p><p>Armed with this knowledge, we can map these locations to imaginary musical instruments hung around the body in 3D space.</p><h3>How does it know which instrument I want to play?</h3><p>Once there’s a human body in the frame, the code divides the area around that body into 6 regions, and waits for left and right hands to enter those regions.</p><p>Those regions are:</p><ul><li>Bottom Left:<br>the area under your left hand, at or below waist height.</li><li>Bottom Right:<br>the area under your right hand, at or below waist height.</li><li>Mid Left:<br>the area to the left of your body, between neck and waist height.</li><li>Mid Right:<br>the area to the right of your body, between nect and waist height.</li><li>Top Left:<br>the area on top of your left shoulder, at or above neck height.</li><li>Top Right: <br>the area on top of your right shoulder, at or above neck height.</li></ul><p>Once a body part (left or right hand) enters a mapped region (say, Bottom<br>right), the instrument (ie, sound) assigned to that region plays.</p><p>Here’s what those 6 regions are mapped to:</p><ul><li>Bottom Left: a drum sound</li><li>Bottom Right: another drum sound</li><li>Mid Left: a cymbal</li><li>Mid Right: another cymbal</li><li>Top Left: a finger snap representing a skipped beat</li><li>Top Right: change mode from Freestyle to Recording, to Playback.</li></ul><blockquote>Note: when trying to “record” a beat, you need to be able to record a “skipped” beat which leaves an empty space during playback. This is what Top Left region is for. Punch up with your left hand in recording mode to record a skipped beat. As validation that a skipped beat did indeed get recorded, you will hear a finger snap sound which doesn’t play back in the `playing` mode.</blockquote><p><strong>How are these regions actually defined in code?</strong></p><p>Some enums first:</p><p>Hand:</p><pre>enum Hand: String {<br>    case leftHand = &quot;leftHand&quot;<br>    case rightHand = &quot;rightHand&quot;<br>}</pre><p>HitPosition, listing the directions where a Hand could be at:</p><pre>enum HitPosition: String {<br>    case neutral = &quot;neutral&quot;<br>    case up = &quot;up&quot;<br>    case down = &quot;down&quot;<br>    case left = &quot;left&quot;<br>    case right = &quot;right&quot;<br>}</pre><p>Beat, a struct to represent a Hand + HitPosition combination that actually creates a sound:</p><pre>struct Beat: Hashable {<br>    var hand: Hand<br>    var hitPosition: HitPosition</pre><pre>init(_ hand: Hand, _ hitPosition: HitPosition) {<br>        self.hand = hand<br>        self.hitPosition = hitPosition<br>    }<br>}</pre><p>Given the above, a drum instrument region is completely defined by a Beat() instance, ie, a Hand &amp; HitPosition combination:</p><p>Here’s what the different regions map to, in code:</p><ul><li>Bottom Left: Beat(.leftHand, .down)</li><li>Bottom Right: Beat(.rightHand, .down)</li><li>Mid Left: Beat(.leftHand, .left)</li><li>Mid Right: Beat(.rightHand, .right)</li><li>Top Left: Beat(.leftHand, .up)</li><li>Top Right: Beat(.rightHand, .up)</li></ul><p>And here’s how those regions map to their respective beat sounds:</p><pre>let beatAudioName: [Beat: String] = [<br>    Beat(.leftHand, .up): &quot;snap&quot;,<br>    Beat(.leftHand, .down): &quot;drum2&quot;,<br>    Beat(.leftHand, .left): &quot;snare2&quot;,<br>    Beat(.rightHand, .down): &quot;drum1&quot;,<br>    Beat(.rightHand, .right): &quot;snare1&quot;,<br>]</pre><blockquote>Notice that there is no beatAudioName for “Top Right” region. That’s because punching the right hand up is used as a gesture for navigating the app between different modes, namely, toggling between recording beats and playing them back.</blockquote><p><strong>“Enter” and “Exit” hresholds for the different regions</strong></p><pre>TOP<br>         -------------------  1  -------------------<br>         |    -------------- 0.8 --------------    |<br>         |    |    --------- 0.7 ---------    |    |<br>         |    |    |                     |    |    |<br>         |    |    |                     |    |    |<br>         |  -0.4  -0.3      (0, 0.5)    0.3  0.4   |<br>         |    |    |                     |    |    |<br> LEFT   -1    |    |                     |    |    1   RIGHT<br>         |    |    --------- 0.2 ---------    |    |<br>         |    -------------- 0.1 --------------    |<br>         |                                         |<br>         |                                         |<br>         |                                         |<br>         |                                         |<br>         |                                         |<br>         ------------------- -1  -------------------<br>                            BOTTOM</pre><p>The numbers in the figure above define the constraints for hands to enter or<br>exit the respective regions.</p><p>If you imagine a person standing with their hands held close to<br>chest in a rest position, then here’s what the numbers above mean.</p><p>LEFT:</p><ul><li>The leftmost “-1” signifies a left hand fully stretched out to the left side.</li><li>“-0.4” signifies the threshold for left hand to “enter” the Mid Left region, in order to play the left hand cymbal sound.</li><li>“-0.3” signifies the threshold for left hand to cross in order to “exit” the Mid left region and come back to middle rest position.</li></ul><p>RIGHT:</p><ul><li>The rightmost “1” signifies a right hand fully stretched out to your right.</li><li>Similar to left hand logic, “0.4” signifies the threshold for right hand to “enter” Mid Right region.</li><li>“0.3” signifies the threshold for right hand to “exit” the Mid Right region.</li></ul><p>TOP:</p><ul><li>The topmost “1” signifies left or right hand fully stretched out to the top.</li><li>“0.8” signifies the vertical threshold for left and right hands to “enter” the Top Left or Top Right region, respectively. To simplify the interaction, left hand can only enter Top Left region, and right hand can only enter the Top Right region.</li><li>“0.7” signifies the vertical threshold to “exit” the Top Left or Top Right region.</li></ul><p>BOTTOM:</p><ul><li>Bottommost “-1” signifies feet, the bottommost point in the body.</li><li>“0.1” signifies the vertical threshold for left and right hands to “enter” the Bottom Left or Bottom Right regions, respectively.</li><li>“0.2” signifies the vertical threshold for hands to “exit” Bottom Left or Bottom Right regions.</li></ul><p>One useful way to think of this constraint scheme is as (max, entry, exit), where:</p><ul><li>max defines the boundary value, the upper bound.</li><li>entry defines the threshold for “entering” a region, and</li><li>exit defines the threshold for “exiting” the region previously entered.</li></ul><p>The reason that I kept separate “enter” and “exit” thresholds for regions is because otherwise, there would be jitter and unpredictable behavior at the boundaries, making the interaction very “noisy” (get it?).</p><p>Keeping the “enter” thresholds harder to reach, and “exit” thresholds lower but require having “enter”ed a region previously, makes hitting the drums very intentional and smooth. It safeguards against small body motion or tracking jitter from affecting the user experience.</p><p><strong>How are these “Enter” and “Exit” thresholds specified in code?</strong></p><p>Here’s how. First, you need a way to signify “entering” vs “exiting”:</p><pre>enum GoingType: String {<br>    case into = &quot;into&quot;<br>    case outof = &quot;outof&quot;<br>}</pre><p>Think of GoingType as specifying whether a hand is going .into a region, or .outof it.</p><p>Given that, here’s how the thresholds are specified:</p><pre>let hitPositionThresholds: [HitPosition: [GoingType: Float]] = [<br>    .up: [.into: 0.8, .outof: 0.7],<br>    .down: [.into: 0.1, .outof: 0.2],<br>    .left: [.into: 0.4, .outof: 0.3],<br>    .right: [.into: -0.4, .outof: -0.3]<br>]</pre><p>Pretty compact, given how much they represent, isn’t it? Love that about Swift enums (and other Swifty data structures).</p><h3>So, what’s the app’s user interface like?</h3><p>Since ARKit Body Tracking only works with the back camera, you can’t actually see yourself playing the drums. This presents an interesting UX challenge.</p><p><strong>How do you design the user interface or UX for something that has no visual UI?</strong></p><p>You design a sensorial interface, of course! Purely auditory, in this case. Meaning you don’t need to <em>see</em> the UI because you can <em>hear</em> it.</p><p>Being about music creation, the main output of this Augmented Reality Drum Set is, in fact, audio. So a purely auditory interface can work just fine as long as other features in the app also produce clearly distinguishable sounds.</p><p><strong>But what about interactions? How do you interact with a non-visual interface?</strong></p><p>With your full body, in this case. So, not only do you bang imaginary drums with your full body, the user interactions are also mapped directly to clearly identifiable body gestures.</p><p>There is only one user interaction gesture in this demo: <strong>punching up with the right hand</strong>, which corresponds to the “Top right” region out of the 6 mapped regions described earlier. Making this gesture progresses the app UI mode from freestyle, to recording, to playing, providing sufficient for navigating the app.</p><p>To summarize:</p><ul><li>Navigate the app using body gestures (like punching up with the right hand).</li><li>Play drums with body gestures, punching and banging all around (except for, you know, punching up with the right hand).</li><li>Listen to, instead of watch, the state of the UI as you navigate through it.</li></ul><blockquote>Even though it’s not required for the user, there still exist visual indications about the state of the app in the UI, just so a recording or a demo makes more sense for someone watching your performance.</blockquote><h3>Hmm, can I try it out?</h3><p>Download <a href="https://apps.apple.com/us/app/tambour/id1493473305">Tambour</a> from iOS App Store for your iPhone or iPad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*Ffg0eJfW1mUhvph3OBTpRw.png" /><figcaption>Tambour on iOS</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b20c9398e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS implemented in a Tweet!]]></title>
            <link>https://asyncanup.medium.com/reactjs-implemented-in-a-tweet-6727ad0ad5a4?source=rss-bec38e5c817d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6727ad0ad5a4</guid>
            <category><![CDATA[tweet]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Anup Bishnoi]]></dc:creator>
            <pubDate>Wed, 25 Nov 2020 09:33:30 GMT</pubDate>
            <atom:updated>2020-11-25T09:34:32.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s implement the basic <a href="https://reactjs.org/">React</a> API in a tweet, with React DOM &amp; State management as a separate plugin in another tweet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*nPrU_beL91nNUo6-ka-DMA.png" /></figure><h3>What we want, and shall get</h3><ul><li>Top-down, one-way, state-driven rendering.</li><li>Compose HTML primitives into higher-level components.</li><li>Ability to write JSX to define components.</li><li>Custom props for higher-order components.</li><li>Event handlers that can change application state and trigger re-renders.</li></ul><h3>What we won’t get</h3><ul><li>No virtual DOM diffing between old and new renders for efficient DOM updates, so re-renders will replace HTML content.</li><li>setState won’t be asynchronous, but synchronous.</li><li>DOM event handlers won’t have React-ified names (like onClick), but default DOM names (like onclick).</li><li>Only necessary API surface area implemented, so <em>yes</em> React.createElement, and <em>no</em> React.cloneElement.</li><li>No <a href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a> API.</li></ul><h3>Code</h3><p>Here’s React defined as a global:</p><pre>React={Component:function(e){this.props=e},[C=&quot;createElement&quot;]:(t,s,...a)=&gt;t.bind?new t(s):(e=document[C](t),(()=&gt;{for(n in s)e[n]=s[n]})(),g(a).map(t=&gt;e[A](t.props?t.render():t.part?t:new Text(t))),e)},g=(e=&gt;(e=e||[],e.map?e.flatMap(g):[e])),A=&quot;appendChild&quot;</pre><p>What does the above do?</p><ul><li>Defines a global <a href="https://reactjs.org/docs/react-api.html">React</a>.</li><li>Defines <a href="https://reactjs.org/docs/react-component.html">React.Component</a>, the component base class.</li><li>Defines <a href="https://reactjs.org/docs/react-api.html#createelement">React.createElement</a> which can create both HTML primitives and custom components.</li><li>React.createElement also accepts props, and children which get appended to the created DOM element.</li><li>JSX essentially transpiles to React.createElement calls, with contents passed in as children argument. These children can be custom components, primitive HTML elements, or plain text. Code handles them all correctly.</li></ul><h3>WHAT! HOW?</h3><p>Read the annotated, prettified code below for line-by-line explanation.</p><p>For now, moving on to more features!</p><h3>React DOM + State management</h3><p>You can bring in React DOM and React’s State management API come as a separate plugin, implemented in another tweet!</p><pre>ReactDOM={render:(e,t)=&gt;(e.h=t,t[A](e.render()))},React.Component.prototype.setState=function(e){this.state={...this.state,...e},this.h.innerHTML=&quot;&quot;,ReactDOM.render(this,this.h)};</pre><p>What does the above define?</p><ul><li>A global ReactDOM.</li><li><a href="https://reactjs.org/docs/react-dom.html#render">ReactDOM.render</a> function to trigger re-renders.</li><li><a href="https://reactjs.org/docs/react-component.html#setstate">React.Component#setState</a> to set component-level state that triggers a re-render of that component.</li></ul><h3>Demo</h3><p>Let’s build React’s own <a href="https://reactjs.org/tutorial/tutorial.html">Tic-tac-toe tutorial</a> with React-in-a-tweet™.</p><p>You can fiddle with the following over at <a href="https://jsfiddle.net/asyncanup/0bzfy1sq/">JSFiddle</a>, or try it out right here!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Fasyncanup%2F0bzfy1sq%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2Fasyncanup%2F0bzfy1sq%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F6a55e6c2e64110793b23129719378cbb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc4bf5614ec4ab878d34e04629e5ef0/href">https://medium.com/media/8fc4bf5614ec4ab878d34e04629e5ef0/href</a></iframe><p>Video of working example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyGxL6uOdFaQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyGxL6uOdFaQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyGxL6uOdFaQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ae5f501bfa3b9d4bfce59de4fc263cc/href">https://medium.com/media/6ae5f501bfa3b9d4bfce59de4fc263cc/href</a></iframe><h3>Usage code</h3><p>Here’s how that sweet sweet demo is implemented.</p><p>Throw in a root HTML element:</p><pre>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</pre><p>Sprinkle some CSS to make things look right (from <a href="https://reactjs.org/tutorial/tutorial.html">React tutorial</a>):</p><pre>body { font: 14px &quot;Century Gothic&quot;, Futura, sans-serif; margin: 20px; }<br>ol, ul { padding-left: 30px; }<br>.board-row:after { clear: both; content: &quot;&quot;; display: table; }<br>.status { margin-bottom: 10px; } <br>.square {<br>  background: #fff; border: 1px solid #999; float: left;<br>  font-size: 24px; font-weight: bold; line-height: 34px;<br>  height: 34px; margin-right: -1px; margin-top: -1px;<br>  padding: 0; text-align: center; width: 34px;<br>}<br>.square:focus { outline: none; }<br>.kbd-navigation .square:focus { background: #ddd; }<br>.game { display: flex; flex-direction: row; }<br>.game-info { margin-left: 20px; }</pre><p>And now the work horse, the JSX-enabled usage of React-in-a-tweet™ (also lifted from <a href="https://reactjs.org/tutorial/tutorial.html">React tutorial</a>):</p><pre>function Square(props) {<br>  return (<br>    &lt;button className=&quot;square&quot; onclick={props.onClick}&gt;<br>      {props.value}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>Returning JSX!</p><p>The way that works is: Babel transpiles this JSX to React.createElement calls, which are handled by React-in-a-tweet just fine.</p><p>Remember, JSX transpiles to React.createElement() calls, and passes in the component type as the first argument, props defined in JSX as the second argument, and any children provided as the third argument.</p><p>For example:</p><pre>&lt;button className=&quot;square&quot; onclick={props.onClick}&gt;<br>  Square value: {props.value}<br>  &lt;div&gt;nested&lt;/div&gt;<br>&lt;/button&gt;</pre><p>transpiles to:</p><pre>React.createElement(&quot;button&quot;, {<br>  className: &quot;square&quot;,<br>  onclick: props.onClick<br>},<br>  &quot;Square value: &quot;, props.value,<br>  React.createElement(&quot;div&quot;, null, &quot;nested&quot;)<br>);</pre><p>So, transpiled code includes React.createElement() calls that contain 3 or more arguments: type, props, and ...children.</p><p>Also notice that the click handler on button above has the DOM-defined name onclick, instead of the name that React gives it - onClick.</p><p>This is because React-in-a-tweet does not implement React’s <a href="https://reactjs.org/docs/handling-events.html#gatsby-focus-wrapper">synthetic events</a>. But, just like React, you can still assign functions to onclick.</p><p>Wait, what about props.onClick though? Why isn’t it it props.onclick? Well, that’s just a prop name, which can be anything you like :)</p><p>Moving on to more definitions:</p><pre>class Board extends React.Component {<br>  renderSquare(i) {<br>    return (<br>      &lt;Square<br>        value={this.props.squares[i]}<br>        onClick={() =&gt; this.props.onClick(i)}<br>      /&gt;<br>    );<br>  }</pre><pre>render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;div className=&quot;board-row&quot;&gt;<br>          {this.renderSquare(0)}<br>          {this.renderSquare(1)}<br>          {this.renderSquare(2)}<br>        &lt;/div&gt;<br>        &lt;div className=&quot;board-row&quot;&gt;<br>          {this.renderSquare(3)}<br>          {this.renderSquare(4)}<br>          {this.renderSquare(5)}<br>        &lt;/div&gt;<br>        &lt;div className=&quot;board-row&quot;&gt;<br>          {this.renderSquare(6)}<br>          {this.renderSquare(7)}<br>          {this.renderSquare(8)}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>Notice how Board’s render function can call this.renderSquare() to fill in parts of the rendered output. Works just fine.</p><p>renderSquare() returns a <em>custom component</em>, Square, not an HTML primitive. Works fine.</p><p>Also notice how the onClick handler defined in renderSquare() is just an arrow function. Works great.</p><p>But wait, what’s className doing there? Isn’t that a React-ified HTML attribute name? Well, no siree. <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/className">className</a> is pure DOM API. Works as is.</p><p>Now let’s define the root game component itself:</p><pre>class Game extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      history: [<br>        {<br>          squares: Array(9).fill(null)<br>        }<br>      ],<br>      stepNumber: 0,<br>      xIsNext: true<br>    };<br>  }</pre><pre>handleClick(i) {<br>    console.log(&#39;handleClick&#39;, i);<br>    const history = this.state.history.slice(0, this.state.stepNumber + 1);<br>    const current = history[history.length - 1];<br>    const squares = current.squares.slice();<br>    if (calculateWinner(squares) || squares[i]) {<br>      return;<br>    }<br>    squares[i] = this.state.xIsNext ? &quot;X&quot; : &quot;O&quot;;<br>    this.setState({<br>      history: history.concat([<br>        {<br>          squares: squares<br>        }<br>      ]),<br>      stepNumber: history.length,<br>      xIsNext: !this.state.xIsNext<br>    });<br>  }</pre><pre>jumpTo(step) {<br>    this.setState({<br>      stepNumber: step,<br>      xIsNext: (step % 2) === 0<br>    });<br>  }</pre><pre>render() {<br>    const history = this.state.history;<br>    const current = history[this.state.stepNumber];<br>    const winner = calculateWinner(current.squares);</pre><pre>const moves = history.map((step, move) =&gt; {<br>      const desc = move ?<br>        &#39;Go to move #&#39; + move :<br>        &#39;Go to game start&#39;;<br>      return (<br>        &lt;li key={move}&gt;<br>          &lt;button onclick={() =&gt; this.jumpTo(move)}&gt;{desc}&lt;/button&gt;<br>        &lt;/li&gt;<br>      );<br>    });</pre><pre>let status;<br>    if (winner) {<br>      status = &quot;Winner: &quot; + winner;<br>    } else {<br>      status = &quot;Next player: &quot; + (this.state.xIsNext ? &quot;X&quot; : &quot;O&quot;);<br>    }</pre><pre>return (<br>      &lt;div className=&quot;game&quot;&gt;<br>        &lt;div className=&quot;game-board&quot;&gt;<br>          &lt;Board<br>            squares={current.squares}<br>            onClick={i =&gt; this.handleClick(i)}<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;game-info&quot;&gt;<br>          &lt;div&gt;{status}&lt;/div&gt;<br>          &lt;ol&gt;{moves}&lt;/ol&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>So much code! Well, as far as React API is concerned, there are only a few interesting things going on in there.</p><ul><li>Game’s constructor sets initial state (this.state), storing history and other Tic-tac-toe-specific data.</li><li>handleClick click handler uses this.setState() and passes in new state.</li><li>render does conditional rendering based on whether the game has been won yet, and returns JSX for the entire game board.</li><li>Since game state is defined entirely as Game’s React state, the entire game board will re-render on every game state change in this example. Regardless of this example, React-in-a-tweet does allow re-rendering specific parts of a UI as long as those specific UI sections hold their own state, instead of depending on a single global state.</li></ul><pre>ReactDOM.render(&lt;Game /&gt;, document.getElementById(&quot;root&quot;));<br>console.log(&#39;✓&#39;)</pre><p>React DOM API that triggers the first-render, y’all. Passing in JSX for &lt;Game /&gt; works. It’s just the React you know and love!</p><p>Finally, a helper function that calculates winner after every move:</p><pre>function calculateWinner(squares) {<br>  const lines = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]];<br>  for (let i = 0; i &lt; lines.length; i++) {<br>    const [a, b, c] = lines[i];<br>    if (squares[a] &amp;&amp; squares[a] === squares[b] &amp;&amp; squares[a] === squares[c]) return squares[a];<br>  }<br>  return null;<br>}</pre><h3>Wait, how does React-in-a-tweet itself work?</h3><p>Glad you asked!</p><p>Here’s a line-by-line explanation of the tweet-sized source code of React-in-a-tweet:</p><p>Define React global:</p><pre>React = {</pre><p>Define and implement the following API:</p><ul><li>React.Component, just a simple base class which stores the props passed to it.</li></ul><pre>    Component: function(p) {<br>      this.props = p<br>    },</pre><ul><li>React.createElement, the work horse of rendering, which accepts:</li><li>t, HTML type name or React component class,</li><li>p, props</li><li>...c, children to be appended to the dom element created.</li></ul><pre>    [C = &#39;createElement&#39;]: (t, p, ...c) =&gt; (</pre><p>In the case of t being a React-in-a-tweet component class, ie, a constructor function derived from React.Component, we can just instantiate that function with passed props and return the resulting React component instance.</p><pre>      t.bind<br>        ? new t(p)</pre><p>Otherwise, t is an HTML primitive element name, like button, or span. In this case, create a new HTML element using document.createElement(t)</p><pre>        : (<br>          e = document[C](t),</pre><p>and assign all the props passed to it as direct properties of the HTML element. This is how onclicks and other event handlers get registered.</p><blockquote><em>If you want to use React-like CSS-in-JS, you can modify the part below to loop over a passed </em><em>style object, and assign its properties to </em><em>e[n].style.</em></blockquote><pre>          (() =&gt; {<br>            for (n in p)<br>              e[n] = p[n]<br>          })(),</pre><p>We must also append the children passed in as arguments into the created DOM element.</p><p>Looping over a flattened list of children, handle the following cases for each child element (e):</p><ul><li>If a.props exists, then it’s a React.Component instance. Call a.render() to get the corresponding instantiated HTML element.</li><li>If a.part exists, then it’s a regular HTML element instance already. Do nothing.</li><li>Else, a must be plain text. Initialize a new HTML Text element to hold the string.</li></ul><p>In all cases, after instantiating, append the resulting DOM element as a child to the parent DOM element e.</p><blockquote><em>Note: </em><em>A is just shorthand for </em><em>appendChild, as defined below.</em></blockquote><p>Finally, return e, the element created and filled in by this execution of React.createElement().</p><pre>          g(c).map(a =&gt; (<br>            e[A](<br>              a.props<br>                ? a.render()<br>                : a.part<br>                  ? a<br>                  : new Text(a)<br>            )<br>          )),<br>          e<br>        )<br>    )<br>},</pre><p>Lastly, define g, just a helper function that flattens elements, lists, and list of lists into a single list, to support React.createElement’s children argument semantics.</p><pre>g = a =&gt; (<br>  a = a || [],<br>  a.map ? a.flatMap(g) : [a]<br>),<br>A = &#39;appendChild&#39;,</pre><p>And that’s it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F4323138&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Famericas-got-talent-agt-happy-smile-excited-gif-4323138&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fimages%2Fc4a44946405b906021c68017c6eb0187%2Fraw&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a85a5e0552edce67468a2533b9ad5eb/href">https://medium.com/media/2a85a5e0552edce67468a2533b9ad5eb/href</a></iframe><blockquote><em>Understanding the React DOM + Component.setState tweet is left as an exercise to the reader.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6727ad0ad5a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>