<?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 Joe Keohan on Medium]]></title>
        <description><![CDATA[Stories by Joe Keohan on Medium]]></description>
        <link>https://medium.com/@jkeohan?source=rss-87d734551255------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jVn-OE7YS6ErG29AHi5kCQ.jpeg</url>
            <title>Stories by Joe Keohan on Medium</title>
            <link>https://medium.com/@jkeohan?source=rss-87d734551255------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:39:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jkeohan/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[React & D3: Adding A Bar Chart]]></title>
            <link>https://medium.com/data-science/react-d3-adding-a-bar-chart-6b29f52d74b6?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b29f52d74b6</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Fri, 18 Dec 2020 01:06:13 GMT</pubDate>
            <atom:updated>2021-04-29T18:52:33.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnH6zO16V9kU28G4hc2-tQ.png" /><figcaption>Image by author</figcaption></figure><p>So the last component to refactor in Streetball Mecca is the bar chart. In my last article, <a href="https://towardsdatascience.com/react-d3-preparing-the-data-with-d3-nest-ca1e31ded011">React &amp; D3: Preparing The Data With D3.Nest,</a> I discussed how the data for the chart was organized and formatted using <strong>d3.nest. </strong>This<strong> </strong>involved grouping the parks based on their neighborhood location and calculating the overall average of all parks associated with that neighborhood.</p><p>Here is the <a href="https://kj9g5.csb.app/">current working version </a>used in this article and the <a href="https://codesandbox.io/s/naughty-heyrovsky-kj9g5?file=/src/components/App/index.js">CodeSandbox </a>as well.</p><h4>Thinking Outside The Box</h4><p>As I started to contemplate how best to refactor the D3 bar chart code into the React ecosystem, I leveraged the lessons learned from all the previous refactoring. One of the most important changes was to allow React to manage state, render/update DOM elements, and then allow D3 to do what it does best, such as creating scales and nesting data.</p><p>For this refactor I decided to take it one step further and opted to take a <strong>non-svg </strong>approach to rendering the bar and circle elements. This decision was born initially from many previous frustrations having to manually position g elements. It was also influenced by the fact that I just taught a class on Flexbox and as part of that prep I came across a bookmark I saved over a year ago to the article<a href="https://pudding.cool/process/flexbox-layout/"> “Making Data Vis Without SVG Using D3 &amp; Flexbox”</a> by Amber Thomas. I felt like the stars had aligned and all the signs pointed to Flexbox.</p><h4>Planning It Out</h4><p>Initially, I had ported over the D3 code and refactored it just slightly to work within a single React BarChart component. This <strong>D3 within React </strong>approach was meant as a first step to understanding how to coerce D3 to work within React. I also kept much of the D3 code intact in order to get something up and running. It however ended up being close to 200 lines of code and started to feel unmanageable.</p><p>Now that I was ready to move forward with the second refactor and take a “<strong>D3 for the math and React for everything else”</strong> approach, the first thing I needed to plan out was the component hierarchy. I used an app called<a href="https://excalidraw.com/"> </a><a href="https://dnn4h.csb.app/">excalidraw</a> to draw out the initial mockup and help work through the though and design process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*8RaaJQdcn5wJngPG7WfgJQ.png" /><figcaption>Image by author</figcaption></figure><h4>BarChart Component</h4><p>The <strong>BarChart </strong>is the first component in this hierarchy so it makes sense to start there. Since both the <strong>XAxis </strong>and <strong>Neighborhoods </strong>components would require the same D3 scale, I decided to create it here and then pass it down to both as a prop.</p><pre>const BarChart = (props) =&gt; {</pre><pre> const margin = { right: 25 };</pre><pre> const xScale = d3.scaleLinear()<br>  .domain([0, 100])<br>  .range([0, 1100 - margin.right]);</pre><pre>return ( <br>   &lt;&gt;<br>    &lt;div id=&quot;axis&quot;&gt;&lt;XAxis xScale={xScale} /&gt;&lt;/div&gt;<br>    &lt;div id=&quot;bar-chart&quot;&gt;<br>      &lt;Neighborhoods {...props} xScale={xScale} /&gt;    <br>    &lt;/div&gt;<br>   &lt;/&gt;<br>  )<br>}</pre><p>D3 has several methods that can be used for creating scales. Scales take an input (usually a number, date, or category) and return a value (such as a coordinate, color, length, or radius). They come in several categories that range from continuous input/output <strong>(d3.scaleLinear()) </strong>to discrete input/output <strong>(d3.scaleOridinal()) </strong>and somewhere in-between <strong>(d3.scaleQuantize()). </strong>Scales themselves could be an entire lecture in their own right so if you’re interested in learning more I highly suggest you read<a href="https://www.d3indepth.com/scales/"> d3indepth.com</a>.</p><p>The scale I needed for this chart would be a dynamic, continuous input/output scale so I went with <strong>d3.scaleLinear(). </strong>All<strong> </strong>D3 scales require that you define a <strong>.domain()</strong> and <strong>.range(). </strong>The <strong>domain </strong>of values used for this scale is based on the overall rating of the parks. They could potentially be in total disrepair and assigned 0 (lowest value possible) or the creme de la creme of parks with a rating of 100 (highest value possible). Here, for example, is the <strong>100% Playground</strong> park located in <strong>Canarsie</strong> Brooklyn which falls somewhere in between with an overall rating of 56.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*r7QYASUYLCzSmFWh9EioEw.png" /><figcaption>Image by author</figcaption></figure><p>The average of those parks was also needed as this would be assigned to the parent neighborhood and I had used <strong>D3.nest()</strong> to rollup those values as seen in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zn5q7fm3UVXSW7py7R2AAw.png" /><figcaption>Image by author</figcaption></figure><p>If you’re curious about working with d3.nest (which I hope you are), you can read more about how I nested the data in my previous article: <a href="https://towardsdatascience.com/react-d3-preparing-the-data-with-d3-nest-ca1e31ded011">Preparing The Data With D3.Nest</a>.</p><p>The <strong>.range()</strong> is based on the pixel space provided to the <strong>.bar-group </strong>element which is assigned a width of <strong>1100px. </strong>I did need to subtract <strong>25px </strong>in order to provide a bit of margin between both, the last tick value(100) and the circle and the right border of the <strong>.bar-group</strong> element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*EaH6LDywOotZ8hRh64aa5g.png" /><figcaption>Image by author</figcaption></figure><p>As you continue to examine more and more D3 code in general, you will see a common pattern of defining a set of margins that are used to define this additional space which is then referenced by the scale but quite possibly throughout the code in key places.</p><pre>const margin = { right: 25 };<br>const xScale = d3.scaleLinear()<br>  .domain([0, 100])<br>  .range([0, 1100 - margin.right]);</pre><p>Almost any D3 tutorial on scales will provide a similar visual in order to convey the relationship between the domain and range so I thought I’d do the same as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2_l6iq8p7sE2J2j4fjf0A.png" /><figcaption>Image by author</figcaption></figure><p><strong>A Little Bit About Axes</strong></p><p>If you have ever worked with D3 in the past, using it to create any one of the more standard chart types such as bar, line, or scatterplot, then it’s safe to say you have some familiarity with adding an axis. If, however, you are new to D3, then know that axes require the following steps:</p><p><strong>Creating a scale </strong>(we did so using d3.scaleLinear())</p><p><strong>Setting its orientation: </strong>the orientation of an axis is fixed, however, it can be changed using one of the<a href="https://github.com/d3/d3-axis"><strong> </strong>four orientation methods</a> — <strong>.axisBottom(), .axisTop(), .axisLeft(), and .axisRight().</strong></p><p><strong>Appending the Axis:</strong> once the axis has been created it is then appended using <strong>.call(xAxis).</strong></p><p>The axis also has additional configurations for setting tick values, sizes, and format.</p><p>Being that I’ll be using React for the DOM and D3 for where it’s best suited, I decided that for this refactor I would only make use of <strong>d3.scaleLinear() </strong>and<strong> </strong>render the ticks using React.</p><h4>XAxis Component</h4><p>The only prop being passed to the <strong>XAxis</strong> component was the <strong>xScale</strong> so I’ll just object de-structure that value to make it clear that this is all that the component needs as it pertains to props.</p><pre>const Axis = ({xScale}) =&gt; {</pre><pre>}</pre><p>For much of the <strong>XAxis</strong> refactor I had used as a reference a beautifully written tutorial on<a href="https://wattenberger.com/blog/react-and-d3#creating-svg-elements"> React &amp; D3 by Amelia Wattenberger,</a> She wrote the article in order to promote her recent book<a href="https://www.newline.co/fullstack-d3"> “Full Stack D3 and Data Visualization”</a>.</p><p>I was, at one point, tempted to buy it and would have done so had I not already owned the following books on D3:</p><ul><li><a href="https://www.manning.com/books/d3js-in-action-second-edition">D3.js In Action by Elijah Meeks (both editions)</a></li><li><a href="https://leanpub.com/reactd3jses6">React &amp; D3v4 by Swizec Teller</a> (along with a video subscription)</li><li><a href="https://www.amazon.com/Developing-D3-Js-Edge-Constructing-Components/dp/9386052725">Developing A D3 Edge by Chris Viau, Andrew Thornton, Ger Hobbelt and Roland Dunn</a></li><li><a href="https://leanpub.com/d3-t-and-t-v6">D3 Tips and Tricks by Malcom Maclean</a></li><li><a href="https://www.amazon.com/Learning-D3-js-Mapping-Thomas-Newton-ebook/dp/B00RP13CPC/ref=sr_1_4?dchild=1&amp;keywords=d3+mapping&amp;qid=1608047139&amp;sr=8-4">Learning D3 Mapping by Thomas Newton and Oscar Villarreal</a></li></ul><p>In Amelia’s article she looped over the array of individual ticks (0, 10, 20, etc.) using <strong>.ticks()</strong> and assigned each of them an <strong>xOffset</strong> value based on the returned value from the <strong>xScale</strong>.</p><pre>const Axis = ({xScale}) =&gt; {</pre><pre> const ticks = xScale.ticks().map((value) =&gt; ({<br>  value,<br>  xOffset: xScale(value)<br> }))</pre><pre>}</pre><p>It’s been a while since I’ve worked on such a low level with scales and forgot that they included a .<strong>ticks()</strong> method that<strong> </strong>returns an array of the ticks.</p><p>For the axis I decided to stay in line with Amelia’s article rendering an <strong>svg</strong> that uses a nested <strong>g element</strong> to position the axis to the right 200px. It then maps over the ticks array and positions each one of those <strong>g elements </strong>which, itself, renders the tick value.</p><pre>const Axis = ({xScale}) =&gt; {<br> <br>const ticks = xScale.ticks().map((value) =&gt; ({<br>  value,<br>  xOffset: xScale(value)<br> }))</pre><pre> return (   <br>  &lt;svg style={{ height: &#39;20px&#39; }}&gt;<br>   &lt;g transform={&#39;translate(200,0)&#39;}&gt;<br>    {ticks.map(({ value, xOffset }) =&gt; (<br>     &lt;g key={value} transform={`translate(${xOffset}, 0)`}&gt;<br>      &lt;text <br>       key={value} <br>       style={{<br>        fontSize: &#39;14px&#39;,<br>        textAnchor: &#39;middle&#39;,<br>        transform: &#39;translateY(20px)&#39;<br>      }}&gt;<br>       {value}<br>      &lt;/text&gt;<br>     &lt;/g&gt;<br>    ))}<br>   &lt;/g&gt;<br>  &lt;/svg&gt;<br> )<br>}</pre><p><strong>Side Note:</strong> I was able to render the ticks as divs using Flexbox, but that solution required creating an additional <strong>xScale</strong> and removing not only an additional 200px but also another 8px for half the font size. Since I felt only one scale was need, I opted to put that solution on the shelf for now.</p><h4>The Neighborhoods Component</h4><p>This component is responsible for mapping over the <strong>nestedData </strong>array and rendering individual <strong>Neighborhood</strong> components. It passes down several props to the child component, including the <strong>dispatch</strong> function which will be passed as an <strong>action</strong> and which the <strong>useReducer </strong>uses to update state. If you’re curious about <strong>useReducer,</strong> take a look at this previous article I wrote:<a href="https://medium.com/swlh/react-managing-complex-state-transitions-with-usereducer-e37536b12944"> Managing Complex State Transitions With useReducer.</a></p><pre>const Neighborhoods = ({<br> nestedData,<br> dispatch,<br> activeNeighborhood,<br> xScale}) =&gt; {</pre><pre> const neighborhoods = nestedData.map((d, i) =&gt; {<br>  return (<br>   &lt;Neighborhood<br>    key={i}<br>    title={d.key}    <br>    parks={d.value.parks}<br>    width={xScale(d.value.avg)}<br>    xScale={xScale}<br>    neighborhood={d}<br>    dispatch={dispatch}<br>    activeNeighborhood={activeNeighborhood}<br>   /&gt;<br>  );<br> });</pre><pre> return ( &lt;&gt;{neighborhoods}&lt;/&gt; )<br>};</pre><h4>The Neighborhood Component</h4><p>This component is responsible for rendering the following elements:</p><ul><li>neighborhood title</li><li>bar — show the average of all parks</li><li>circles — one for every park</li></ul><p>It also makes use of the following hooks:</p><ul><li><strong>useState </strong>— used to keep track of its active status which is used assign a background color the entire element when the user clicks and it becomes the active neighborhood</li><li><strong>useEffect </strong>— used to update global state if it determines to set the activeNeighborhood value to this neighborhood</li></ul><pre>const Neighborhood = ({<br> parks, <br> width, <br> xScale, <br> title, <br> dispatch, <br> neighborhood,    <br> activeNeighborhood<br>}) =&gt; {</pre><pre> const [active, setActive] = useState(false);</pre><pre> useEffect(() =&gt; {<br>   activeNeighborhood === title ? <br>     setActive(true) : setActive(false);<br>  }, [activeNeighborhood, title]);</pre><pre> // more code...<br>}</pre><p>The next step is to map over the <strong>parks array</strong> and create a <strong>Circle</strong> component. One thing to note is that the element determines how many pixels it should position itself left using the <strong>xScale</strong> but it also needs to subtract 5px. These additional pixels were needed in order to move the circle left, to center it directly under the axis value.</p><pre>const circles = parks.map((d, i) =&gt; {<br> return (<br>  &lt;Circle<br>   key={i}<br>   dispatch={dispatch}<br>   color={d.color}<br>   park={d}<br>   left={xScale(+d.overall) - 5}<br>  /&gt;<br> );<br>});</pre><p>Let’s break down the return statement in the map of the <strong>Neighborhood </strong>component as there are a few things happening here.</p><pre>const neighborhoods = nestedData.map((d, i) =&gt; {<br>  return (<br>   &lt;Neighborhood<br>    key={i}<br>    title={d.key}    <br>    parks={d.value.parks}<br>    width={xScale(d.value.avg)}<br>    xScale={xScale}<br>    neighborhood={d}<br>    dispatch={dispatch}<br>    activeNeighborhood={activeNeighborhood}<br>   /&gt;<br>  );<br> });</pre><p>First, the neighborhood element will reference the <strong>activeNeighborhood </strong>value in state to determine if it needs to highlight its background color in order to indicate it is the active neighborhood as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rg-Dblrb7tAYaVB1L6wrWw.png" /><figcaption>Image by author</figcaption></figure><p>I opted to allow the user to click anywhere in on the element in order to trigger the <strong>onClick </strong>event which calls the <strong>dispatch</strong> function and passes it an object containing a <strong>type</strong> and <strong>payload</strong> as required by <strong>useReducer</strong>. You can read more about working with useReducer and actions in this article: <a href="https://medium.com/swlh/react-managing-complex-state-transitions-with-usereducer-e37536b12944">React: Managing Complex State Transitions With useReducer.</a></p><pre>return (<br> &lt;div <br>  className=&quot;neighborhood&quot;<br>  style={{ background: active ? &#39;lightyellow&#39; : &#39;&#39; }}<br>  onClick={() =&gt; dispatch({<br>   type: &#39;FILTER_ACTIVE_NEIGHBORHOOD&#39;,<br>   payload: { neighborhood }<br>  })}&gt;</pre><pre> // more code...<br> &lt;/div&gt;<br>)</pre><p>Next, we have to render the neighborhood title and assign it a specific color based on which borough it belongs to.</p><pre>return (<br> &lt;div <br>  className=&quot;neighborhood&quot;<br>  style={{ background: active ? &#39;lightyellow&#39; : &#39;&#39; }}<br>  onClick={() =&gt; dispatch({<br>   type: &#39;FILTER_ACTIVE_NEIGHBORHOOD&#39;,<br>   payload: { neighborhood }<br>  })}&gt;<br> <br>  &lt;div <br>   className=&quot;title&quot;<br>   style={{ color: parks[0].boroughColor }}<br>   &gt; {title} &lt;/div&gt;</pre><pre> // more code...<br> &lt;/div&gt;<br>)</pre><p>And finally, the Bars and Circles needed to be rendered. The Bar component requires the <strong>width </strong>value<strong> </strong>which was calculated using the <strong>xScale </strong>along with the entire neighborhood object as key data points are needed by the tooltip.</p><pre>return (<br> &lt;div <br>  className=&quot;neighborhood&quot;<br>  style={{ background: active ? &#39;lightyellow&#39; : &#39;&#39; }}<br>  onClick={() =&gt; dispatch({<br>   type: &#39;FILTER_ACTIVE_NEIGHBORHOOD&#39;,<br>   payload: { neighborhood }<br>  })}&gt;<br> <br>  &lt;div <br>   className=&quot;title&quot;<br>   style={{ color: parks[0].boroughColor }}<br>   &gt; {title} &lt;/div&gt;<br>  <br>  &lt;div className=&quot;bar-group&quot;&gt;<br>   &lt;Bar width={width} neighborhood={neighborhood}/&gt;<br>   {circles}<br>  &lt;/div&gt;</pre><pre> &lt;/div&gt;<br>)</pre><p>Flexbox was enabled on the</p><h4><strong>The Bar Component</strong></h4><p>This component would require the logic needed to render a tooltip when the user hovered over the colored bar. That logic involves adding both <strong>onMouseMove</strong> and <strong>onMouseOut</strong> event listeners and updating a local version of state in order to trigger the re-render.</p><p>The first step to take was create the following state values:</p><ul><li>toolTipCoords — this stores the left and top values to position the tooltip</li><li>isActive — this determines if the tooltip is active</li></ul><pre>const Bar = ({ width, neighborhood }) =&gt; {<br>  const [toolTipCoords, setToolTipCoords] = useState(null)<br>  const [isActive, setIsActive] = useState(false)</pre><pre>  // more code...</pre><pre>}</pre><p>Now we add the handler functions for the event listeners. For this I had to do a bit of research as the standard event object’s<strong> e.pageY, e.clientY, </strong>and<strong> e.screenY </strong>were returning values that were much greater than the actual position of the mouse. I ended up using <strong>e.nativeEvent.offsetX </strong>and <strong>e.nativeEvent.offsetY</strong> and pulled some of that insight right from the <a href="https://reactjs.org/docs/events.html">React docs</a> themselves:</p><blockquote>If you find that you need the underlying browser event for some reason, simply use the nativeEvent attribute to get it. The synthetic events are different from, and do not map directly to, the browser’s native events. For example in onMouseLeave event.nativeEvent will point to a mouseout event.</blockquote><pre>const Bar = ({ width, neighborhood }) =&gt; {<br>  const [toolTipCoords, setToolTipCoords] = useState(null)<br>  const [isActive, setIsActive] = useState(false)</pre><pre>  const handleMouseOut = () =&gt; setIsActive(false)</pre><pre>  const handleMouseOver = (e) =&gt; {<br>   const top = e.nativeEvent.offsetY - 60;<br>   const left = e.nativeEvent.offsetX;<br>   setToolTipCoords({ top, left });<br>   setIsActive(true);<br>};</pre><pre>// more code...</pre><pre>}</pre><p>All that was left was to return the DOM elements configured, assign the event listeners and add some conditional logic to render the tooltip only when <strong>isActive </strong>was <strong>true.</strong></p><pre>const Bar = ({ width, neighborhood }) =&gt; {<br>  const [toolTipCoords, setToolTipCoords] = useState(null)<br>  const [isActive, setIsActive] = useState(false)</pre><pre> const handleMouseOut = () =&gt; setIsActive(false)</pre><pre> const handleMouseOver = (e) =&gt; {<br>   const top = e.nativeEvent.offsetY - 60;<br>   const left = e.nativeEvent.offsetX;<br>   setToolTipCoords({ top, left });<br>   setIsActive(true);<br> }; </pre><pre> return (<br>  &lt;&gt;<br>   &lt;div<br>    className=&quot;bar&quot;<br>    style={{ width: width }}<br>    onMouseMove={(e) =&gt; handleMouseOver(e)}<br>    onMouseOut={() =&gt; handleMouseOut()}<br>    &gt;&lt;/div&gt;<br>    {isActive &amp;&amp; (<br>      &lt;ToolTip coords={toolTipCoords} neighborhood={neighborhood} /&gt;<br>    )}<br>  &lt;/&gt;<br> );<br>}</pre><h4>The Circle Component</h4><p>This component required a much of the same logic for the tooltip as was needed for the Bar component along with one additional onClick event listener that filtered the map for the selected park.</p><p>The <strong>handleClick</strong> function required the use of <strong>e.stopPropagation() </strong>in order<strong> </strong>to prevent the event from bubbling up to the Neighborhood component where an additional onClick event was configured. I found that without <strong>e.stopPropagation()</strong>, all parks, from that neighborhood, would be rendered within the map instead of just that single park.</p><pre>const Circle = ({<br> color, left, park, dispatch}) =&gt; {<br> <br> const [toolTipCoords, setToolTipCoords] = useState(null);<br> const [isActive, setIsActive] = useState(false);</pre><pre> const handleClick = (e) =&gt; {<br> e.stopPropagation()<br> dispatch({ type: &#39;FILTER_ACTIVE_PARK&#39;, payload: { park } })<br> }<br> <br> const handleMouseOut = () =&gt; {<br>  setIsActive(false);<br> };</pre><pre> const handleMouseOver = (e) =&gt; {<br>  const top = e.nativeEvent.offsetY - 90;<br>  const left = e.clientX - 500;<br>  setToolTipCoords({ top, left });  <br> };</pre><h4>Flexbox CSS</h4><p>I had looked forward to using fancy Flexbox properties for this particular layout but it turned out it was only needed enable it on the <strong>neighborhood </strong>and <strong>title </strong>elements.</p><p>Here are is the actual html layout of the <strong>.neighborhood</strong> element and its children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*1YYq6qfnu--mzWfU_X4d4A.png" /><figcaption>Image by author</figcaption></figure><p>Those elements, along with their corresponding CSS rendered as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrtomFPf8SwcbYP5e34l2Q.png" /><figcaption>Image by author</figcaption></figure><p>As for <strong>Flexbox </strong>I first enabled it on the <strong>.neighborhood </strong>element which positioned the title and bar-group horizontally to one another.</p><pre>.neighborhood {<br> display: flex;<br> height: 28px;<br> margin-bottom: 5px;<br>}</pre><p>The <strong>.title </strong>element was also assigned a display of <strong>flex </strong>and used <strong>align-items</strong> to to vertically center the title text</p><pre>.title {<br> display: <em>flex</em>;<br> align-items: <em>center</em>;<br> width:200px;<br>}</pre><h3>Conclusion</h3><p>This is the 7th article of my <strong>Streetball Mecca</strong> series, where I document refactoring the project from its humble beginnings as a<a href="https://codepen.io/jkeohan/project/editor/ZvKkKE"> D3 visualization</a> over to a React build to manage state and the DOM and use D3 for its unique helper functions.</p><p>Thus far, I’ve replaced all instances of <strong>D3’s Enter/Update/Exit </strong>with either React’s <strong>useReducer</strong> or <strong>useState </strong>hooks.<strong> useReducer </strong>is being used to manage the global state and overall business logic of the app, and<strong> useState</strong> is used for more localized state as in the tooltips. Although React took the reins here, D3 was used for what it does best; creating scales (d3.scaleLinear), rendering geo-projections (d3.geoMercator/d3.geoPath), and nesting data (d3.nest).</p><p>This project has certainly helped validate my opinion that React is by far the better choice for managing state and the overall flow of the application logic. Besides all the native React hooks used, such as useReducer, useState, useRef, and useCallback, I also leveraged a few custom hooks such as useDataApi, useOnClickOutside, and useLocalStorage. My favorite part of the refactor has been working with the <strong>React-Spring </strong>animation library<strong> </strong>in order to replace all the D3 transitions. A close runner up was building a bar chart using DIV’s and Flexbox instead of SVGs and G elements, something I’ve wanted to try for some time.</p><p>I certainly have a new appreciation for both libraries and look forward to building more interactive dashboards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b29f52d74b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/react-d3-adding-a-bar-chart-6b29f52d74b6">React &amp; D3: Adding A Bar Chart</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React & D3: Preparing The Data With D3.Nest]]></title>
            <link>https://medium.com/data-science/react-d3-preparing-the-data-with-d3-nest-ca1e31ded011?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1e31ded011</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Thu, 03 Dec 2020 19:27:22 GMT</pubDate>
            <atom:updated>2020-12-03T21:00:59.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*haZexMoig4mZzNHg" /><figcaption>Image by author</figcaption></figure><p>The last and final item to refactor for Streetball Mecca is the interactive bar chart. At this point, I have basically rewritten the entire codebase from <a href="https://codepen.io/jkeohan/project/editor/ZvKkKE">D3</a> over to <a href="https://codesandbox.io/s/confident-sid-ie69p?file=/src/components/BarChart/index_react.js">React</a>. The initial migration over to React took the <strong>D3 within React </strong>approach where D3 was used for data binding, rendering, and updating the DOM elements. Once I got things to work within the React ecosystem, I then refactored for a more <strong>D3 for the math and React for everything else </strong>approach. I’m still looking for a much shorter phrase to capture that concept so if you have any suggestions please send them my way!</p><h3>Nesting The Data Using D3.Nest</h3><p>For this article, I decided to focus solely on walking through the process of coercing the data into nested format in order to render the bar chart. Nesting the data had already been done in the original CodePen and, although this required no further edits, I thought it represented an opportunity to highlight the awesome power of D3’s helper functions, like <strong>d3.nest</strong>.</p><p>Although React was able to take on state management, DOM rendering, and event handling, D3 still had a vital role in the codebase, in this case, nesting the data.</p><h4>The Original Dataset</h4><p>The original data set consisted of an array of 306 individual parks with each one organized as an object of key:value pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*rCfJGPgrf4TBJX7v" /><figcaption>Image by author</figcaption></figure><h4>Nesting Parks By Neighborhood</h4><p>In order to render the bar chart, the data needed to be reorganized into another format. Each park included a key called <strong>neighborhood </strong>and was assigned the value of the neighborhood in which the park was located. That became the starting point to nest the data and include the corresponding parks as a nested array.</p><p>The overall average of all parks within the neighborhood was also needed, as well as the borough and neighborhood code. Using <strong>d3.nest</strong> I was able to create the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Mo0CBeoaYugF58q2" /><figcaption>Image by author</figcaption></figure><p><strong>d3.nest</strong> is one of D3’s data formatting methods. It nests data based on a defined <strong>key </strong>and stores all related data in a value<strong> </strong>object<strong>. </strong>Both <strong>key</strong> and <strong>value</strong> are hard coded into the method, although we have the ability to add any additional supporting keys of our choosing.</p><h4>Documenting Errors/Issues/Resolutions</h4><p>Copying &amp; pasting the code didn’t initially work as the D3 library had made some changes from 5.7 =&gt; 6.2. When I received the initial error I decided to include it along with other errors/issues/resolutions I had been documenting. I too often find myself trying to resolve the same error knowing full well that I’ve already resolved it in a previous project.</p><p>Here is the format I’ve been using to capture/record any error/issue/resolution encountered during the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*GONxN3PjKfjB49t5" /><figcaption>Image by author</figcaption></figure><p>The issue turned out being that <strong>d3.nest</strong> was no longer supported in D3v6 and needed to be imported from<a href="https://github.com/d3/d3-collection"> d3-collection</a>. Ironically enough, just as I went to add the link from the d3.collection page I noticed the following deprecation message which states to use <strong>d3-array’s group </strong>and <strong>rollup</strong> methods instead of <strong>d3.nest.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*719vK7Bjc_KGXGp_" /><figcaption>Image taken from the D3 docs</figcaption></figure><p>In all honesty, I did invest a few minutes trying to refactor d3.nest over the new methods but didn’t quite get it to work so I decided to put that aside for now and save it for a future article. With the way technology progresses I’ll never be pressed to find new and interesting topics to write about.</p><h4>Importing And Using The Libraries</h4><p>The first thing we need to do in order to work with d3.nest is to import <strong>{nest}</strong> from <strong>d3-collection</strong>, along with<strong> d3</strong> as I needed one additional helper method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*AerrToCeCG_KxvCY" /><figcaption>Image by author</figcaption></figure><p><strong>d3.nest</strong> makes use of the following methods:</p><ul><li>.key — the main key value used to nest the data</li><li>.rollup — provides the opportunity to include new key:values</li><li>.entries — the dataset to be mapped over</li></ul><p>The .<strong>key()</strong> method is fairly basic and takes in a callback that is used to determine the top level values by which to nest the data and .<strong>entries() </strong>is then passed the data array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*yx0dm58FuElf6sgm" /><figcaption>Image by author</figcaption></figure><p><strong>.rollup()</strong> does the bulk of the work here and is used to return an object that includes an array of nested child elements along with any additional data points you may need from the dataset.</p><p>It was here that I made use of<a href="https://github.com/d3/d3-array#mean"> d3.mean</a>, which is one of the many<a href="https://github.com/d3/d3-array#mean"> d3.array</a> methods. <strong>d3.mean</strong> was used to return the average of the overall scores assigned to each park in that neighborhood.</p><p>This is once instance where the power of D3 truly shines as a data visualization library. Not only does it provide the methods to visualize data, such as building out the bar chart and axes, but also its tools format the data as well.</p><p>The parks are then rolled up into an array called <strong>parks</strong> and all the data points are stored in a <strong>value</strong> key to produce the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*v9Ie_9R3g1oOvi7T" /><figcaption>Image by author</figcaption></figure><h3>Conclusion</h3><p>This project has taken much longer to work through than I anticipated and required quite a bit of research along the way. Working through the refactor I had the opportunity to revisit D3 specific concepts that I haven’t worked with in quite some time, like <strong>d3.nest</strong>. It’s still a great option to use when nesting data.</p><p>Here is the link to the<a href="https://codesandbox.io/s/d3-streetball-mecca-react-using-react-spring-to-crossfade-images-medium-jkzmc?file=/src/services/format/formatGoogleData.js"> CodeSandbox</a> d3.nest example if you wanted to take a further look. As always, if you have any feedback or comments I’d love to hear them.</p><h3>Additional Articles</h3><p>Here are some additional articles I’ve written on refactoring the code from D3 =&gt; React.</p><ul><li><a href="https://jkeohan.medium.com/react-using-react-spring-to-animate-crossfading-images-1fee000e310d">React &amp; D3: Using React To Crossfade Images</a></li><li><a href="https://jkeohan.medium.com/the-used3-custom-hook-889ddbd30f18">Experimenting With The useD3 Custom Hook</a></li><li><a href="https://levelup.gitconnected.com/react-d3-rendering-a-map-5e006b2f4895">React &amp; D3: Rendering A Map</a></li><li><a href="https://medium.com/swlh/react-managing-complex-state-transitions-with-usereducer-e37536b12944">React: Managing Complex State Transitions With useReducer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1e31ded011" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/react-d3-preparing-the-data-with-d3-nest-ca1e31ded011">React &amp; D3: Preparing The Data With D3.Nest</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React: Using React-Spring To Animate Crossfading Images]]></title>
            <link>https://itnext.io/react-using-react-spring-to-animate-crossfading-images-1fee000e310d?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fee000e310d</guid>
            <category><![CDATA[react-spring]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 16:33:34 GMT</pubDate>
            <atom:updated>2021-01-11T08:01:06.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBfclHr26HNuplpY6dR3mQ.png" /><figcaption>Image by author</figcaption></figure><p>During the refactor of Streetball Mecca from a version using only D3 to a version that leverages D3 for it’s helper functions and React for everything else, I replaced <strong>d3.transition </strong>with<strong> React-Spring</strong> in order to animate the fadein/fadeout of the circles on the map. You can read more about how I implemented that solution in this previous article:<a href="https://jkeohan.medium.com/react-d3-rendering-circles-on-a-map-b7746600502"> React &amp; D3: Rendering Circles On A Map Using React-Spring Transitions</a>.</p><p>While I was refactoring the park image into its own component, I once again found the need to replace <strong>d3.transition</strong> with an alternative solution and decided to give React-Spring another try.</p><h3>The React-Spring Docs And More Research</h3><p>The <strong>d3.transition</strong> used to fadein the park images felt somewhat choppy. The reason being is that it just replaced the previous background image first and then used opacity to create the fadein. Here is the original code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*08tD2r6kmSsp-u8vO4EP7Q.png" /><figcaption>Image by author</figcaption></figure><p>I was never quite happy with that UX implementation and always wanted to apply a smooth crossfade between the incoming/outgoing images. I also knew that this would require a refactor of the original D3 code but I had already reached the point in that project where things worked well enough and needed to move onto the next D3 project.</p><p>However, I was now presented with the opportunity to implement the crossfade, along with another reason to work with React-Spring.</p><h4>Working Example</h4><p>The first thing I did was review the docs to hopefully find a working example of crossfading images. React-Spring provides several methods to work with and after looking over the docs the<a href="https://www.react-spring.io/docs/hooks/use-transition"> useTransition</a> hook caught my eye so I started there.</p><p>I browsed down to the demo samples provided and in less than 30 secondsI found a working example that<a href="https://codesandbox.io/embed/morr206pv8"> looped over transitioning 4 images</a> in a continuous loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmFC_Wc7br7zCbHGkRqGWA.png" /><figcaption>Image from React-Spring demo</figcaption></figure><p>After reviewing the code it was obvious that <strong>useTransition</strong> was being used to control the transitions but I felt I needed to do some additional research to get a better understanding on how it differed from <strong>useSpring</strong>.</p><h4>Additional Research</h4><p>So I did a Google search for <strong>‘useTransition vs useSpring’</strong> and came across the article<a href="https://alligator.io/react/advanced-react-spring/"> “Creating Complex Animation in React using react-spring”</a> written by Joshua Hall. In it he discusses use cases for <strong>useSpring</strong>, <strong>useSprings</strong>, <strong>useTrail,</strong> and <strong>useTransition</strong> and I felt the article really provided the additional context I was looking for.</p><p>As for the comparison between <strong>useSpring</strong> and<strong> useTransition</strong> he states that:</p><blockquote>One problem with useSpring is that it doesn’t give us any control over the lifecycle of our component</blockquote><p>And further followed by:</p><blockquote>Instead we can use useTransition to control the animations as it is mounted and unmounted from the view.</blockquote><p>Although this was my first attempt at working with <strong>useTransition </strong>I did recall implementing animations using several class lifecycle methods once before. So after searching through the hundreds of codepens I’ve written over the years I came across<a href="https://codepen.io/jkeohan/pen/VyGLOM?editors=0010"> animating the alphabet</a> (Jan 2018) which implemented the animations using the<a href="https://reactcommunity.org/react-transition-group/transition"> React-Transition-Group</a> library.</p><p>It was written using class Components and made use of the lifecycle methods <strong>componentWillEnter </strong>and<strong> componentWillLeave</strong>, of which I had never seen before that time, and <strong>componentWillReceiveProps.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*vjS3CZDwpatE21O74MjJNA.png" /><figcaption>Image by author</figcaption></figure><p>In the working example, <strong>useTransition </strong>had also been configured to make use of the keywords<strong> ‘enter’</strong> and<strong> ‘leave’</strong> so it was clear now how it would trigger the animations to coincide with the above lifecycle methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrFa03hyCtSgpDoGJAgVeQ.png" /><figcaption>Image by author</figcaption></figure><p>Also in the example, I could see that <strong>setInterval </strong>was updating the index state value every 5 seconds and that during the re-render a new <strong>useTransition</strong> would be instantiated and assigned that new value.</p><p><strong>useTransition</strong> returned an array which was then mapped over and returned a new <strong>animated.div </strong>with each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0B8_tJYpxbtwj7K-zgZjvg.png" /><figcaption>Image by author</figcaption></figure><h4>More Understanding Required</h4><p>I wasn’t quite sure what was included in the transitions array and I was still curious to understand the entire process so I added console log to take a look.</p><p>I let it run a few times and noticed a pattern. When the next image was about to be displayed the array would contain 3 elements, 2 for leave and 1 for enter. Once the image was faded in, the array would remove the leave at the first position and update <strong>enter </strong>to <strong>update</strong> for the last.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*tYeLn7teJRjSq0mxnRQUrQ.png" /><figcaption>Image by author</figcaption></figure><p>So it seemed that <strong>useTransition</strong> would remove that element from the array once the transition was completed and the element removed from the DOM. I also noticed that the <strong>key</strong> value would keep incrementing and associated with the standard way React keeps track of elements rendered via a map.</p><p>Here is the full code sample from the working example so you can see how it all ties together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dlLfr1wNb7KuQZ57V76UeA.png" /><figcaption>Image by author</figcaption></figure><p>I now felt like I had a grasp of what was going on and decided it was time to apply this understanding to transitioning the park images.</p><h4>Implementing The Transitions</h4><p>The first step was to import the <strong>useTransition</strong> and <strong>animated </strong>methods from React Spring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*gN1sxjLQZv6145xECu_H5g.png" /><figcaption>Image by author</figcaption></figure><p>In the working example, <strong>useTransition</strong> was reassigned a new image based on updated index value. In my configuration, however, the images are being passed down as props.</p><p>Since the component is being re-rendered each time new props are passed it made sense to assign the current prop value to <strong>useTransition</strong>, which in this case was the <strong>activePark </strong>object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tpfTW8nsCQb3R87F1msyw.png" /><figcaption>Image by author</figcaption></figure><p>I also added a console log to see if the transitions would follow the same pattern as before. The pattern was similar although the arrays included one less element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2gztrMjU2FBl8NtmtxCa0g.png" /><figcaption>Image by author</figcaption></figure><p>Not quite sure why the change, but I’m certain if this weighs on my developer conscience long enough, I will revisit it at a later time and try to figure it out.</p><h4>Rendering The Images</h4><p>As for rendering the images I was able to reuse all of the code in the working example, with only a few edits. One of those edits was the need to include some conditional logic to run when the <strong>activePark</strong> object existed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5WCML7tIYPuE5W4lFDoBw.png" /><figcaption>Image by author</figcaption></figure><p>I also added a console log to see what was inside of the map. The elements aligned with what I expected. The <strong>item</strong> was the <strong>activePark object,</strong> the <strong>props</strong> were the <strong>transitions,</strong> and the <strong>key </strong>corresponded to the elements which was how <strong>useTransition</strong> kept track of them as they were rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynYtxm5vi0-SpITBE62ouQ.png" /><figcaption>Image by author</figcaption></figure><p>The key value would then increase every time a new image was rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4ZQHSE3UuoRVrKTyRoFMw.png" /><figcaption>Image by author</figcaption></figure><h3>Conclusion</h3><p>This refactor from <strong>d3.transition</strong> to React-Spring <strong>useTransition</strong> was fairly easy. Along the way I made some discoveries and feel I now have a much better understanding of what’s happening under the hood. It’s moments like these that I realize how my students must feel when they want to know the why but we only had time to teach the how.</p><p>I did work through another solution originally that was a bit more complex and made use of useState and useEffect along with alternating the placement of images in an array.</p><p>It wasn’t until I started writing this article and documenting my thoughts that I decided to refactor that solution. I had the gut feeling it was too complicated and a simpler approach could be found.</p><p>Anyway here is the <a href="https://codesandbox.io/s/d3-streetball-mecca-react-using-react-spring-to-crossfade-images-medium-jkzmc?file=/src/components/ParkInfo/ParkImage/image-spring.js">CodeSandbox </a>if you wanted to take a further look.</p><h3>Additional Articles</h3><p>Here are some additional articles I’ve written as per refactoring the code from D3 =&gt; React. If you have any thoughts, suggestions or comments I’d love to hear them.</p><ul><li><a href="https://jkeohan.medium.com/the-used3-custom-hook-889ddbd30f18">Experimenting With The useD3 Custom Hook</a></li><li><a href="https://levelup.gitconnected.com/react-d3-rendering-a-map-5e006b2f4895">React &amp; D3: Rendering A Map</a></li><li><a href="https://medium.com/swlh/react-managing-complex-state-transitions-with-usereducer-e37536b12944">React: Managing Complex State Transitions With useReducer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fee000e310d" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/react-using-react-spring-to-animate-crossfading-images-1fee000e310d">React: Using React-Spring To Animate Crossfading Images</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React & D3: Rendering Circles On A Map]]></title>
            <link>https://medium.com/data-science/react-d3-rendering-circles-on-a-map-b7746600502?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7746600502</guid>
            <category><![CDATA[react-spring]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 15:25:38 GMT</pubDate>
            <atom:updated>2020-11-30T19:27:03.378Z</atom:updated>
            <content:encoded><![CDATA[<h3>React &amp; D3: Rendering Circles On A Map Using React-Spring Transitions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0RA8idz87TW2vbRcR_hCg.png" /><figcaption>Image by author</figcaption></figure><p>In my last article <a href="https://levelup.gitconnected.com/react-d3-rendering-a-map-5e006b2f4895">React &amp; D3: Rendering A Map</a> I walked through the code to render a map using both the <strong>D3 within React </strong>and <strong>D3(math)/React(DOM)</strong> approaches. It’s a great entry point for anyone with D3 expertise but relatively new to the React.</p><p>In this article I will perform one last refactor to render the circles using the <strong>D3(math)/React(DOM) </strong>approach. This means I’ll be migrating as much of the code from D3 over to React, which in this case is almost all of it.</p><h4>Existing Circle Codebase (D3v4)</h4><p>Here is how I originally wrote the existing D3 specific code. It follows the older D3 (pre V5) <strong>Enter/Update/Exit</strong> pattern and includes the transitions to fade in/out the circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRizkcF-cUOpKG6OfuBPyA.png" /><figcaption>Image by author</figcaption></figure><h4>Small Refactor Of Existing Codebase from D3v4 To D3v5</h4><p>Since I’ve been so focused on working with React these days I really haven’t kept up with any of the new additions to <strong>D3v5/v6</strong>. So i thought to myself maybe this was a good opportunity to refactor the code slightly to incorporate the <strong>d3.join() </strong>method that was introduced in v5 and replace the older Enter/Update/Exit pattern.</p><p>For the record I’ve never worked with <strong>d3.join() </strong>before and was able to implement the code fairly easy, with one small bump which I’ll speak to shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmPRKhsf0am1sYX6yVih5A.png" /><figcaption>Image by author</figcaption></figure><p>This approach requires a bit more code including 3 separate callbacks for each of the Enter/Update/Exit phases. It requires additional callbacks via <strong>.call()</strong> to execute the transitions. I’m not completely sold on this approach and have a hard time seeing the benefits of the additional code.</p><p>I also encountered one small issue where transitions didn’t occur if I didn’t include the <strong>update </strong>callback function. Since I’m not updating any of the circles, and didn’t include any updates in the previous code, I was surprised I needed it. It seems I’ll have to delve a bit further at some point to understand what’s truly going on here.</p><h3>The Circle Components</h3><p>After refactoring the map, it became quite clear that the circles could easily be spun off into their own components. I originally thought about including that code inside of the Map component, but the circles might require their useState or useEffect in order to manage the transitions.</p><p>Inside of the Map folder I created two new folders. One was responsible for rendering all the circles, and the other the actual Circle component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*-Uy37Zi9OT6PdRgJs8sMbA.png" /><figcaption>Image by author</figcaption></figure><h4>The Circles Component</h4><p>Let’s start with the <strong>Circles</strong> component. This really was just a function that would iterate over the array of data and render individual <strong>Circle </strong>components.</p><p>I took this approach as its a standard way of segmenting code used for rendering structured elements like <strong>ul &gt; li’s</strong> as in a <strong>TodoList </strong>and <strong>TodoListItem.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*LA3LYBzOUk114Q8AcNf-_Q.png" /><figcaption>Image by author</figcaption></figure><p>The component required the following props:</p><ul><li><strong>allParks / activeParks arrays</strong></li><li><strong>map projection</strong></li></ul><p>It loops over the<strong> allParks </strong>array and then sets the <strong>isShowing</strong> prop to true/false depending if the park is included in the <strong>activeParks </strong>array. That value will change depending on any user interaction that filters the data causing a re-render.</p><p>Iterating over the array and using the key property to allow React to manage those elements, essentially replaces <strong>D3’s</strong> <strong>Data Binding &amp; Enter/Exit </strong>methods and the <strong>isShowing</strong> prop replaces the <strong>Update </strong>functionality.</p><p>I feel as though there may be another solution that involves using the Circle component’s <strong>componentWillUnmount </strong>lifecycle method to control the transition just before it’s removed from the DOM but this worked for now so I ran with it.</p><h4>The Circle Component</h4><p>So this one took the most time to implement. I needed to replace the <strong>d3.transition</strong> method with another implementation of CSS transitions. After some research I decided to go with <a href="https://www.react-spring.io/">React-Spring</a>. The two main features of React-Spring that I used were the <strong>useSpring </strong>hook and <strong>animated.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*huXR2v0WAYuhpuPs2mpMeA.png" /><figcaption>Image by author</figcaption></figure><p>Let’s break down the <strong>React-Spring</strong> code a bit further. The <strong>useSpring</strong> hook takes in an object that includes a <strong>config </strong>for any configurations. In this case I only needed to include the duration but there are other config options available.</p><p>The other key I added was to target the specific CSS property to transition, in this case opacity. Also being that its JS I was able to use a ternary operator to conditionally render that value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*er88Qf5VddhfMwQnUP6Q8Q.png" /><figcaption>Image by author</figcaption></figure><p>The next step was to prepend the circle element with <strong>animated. </strong>This immediately reminded me <strong>Styled Components </strong>in that they are written in a similar syntax where the DOM element is preceded by styled as in: <strong>styled.circle``</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*2sBNtBgf-0bDS-ttsMKYVw.png" /><figcaption>Image by author</figcaption></figure><p>Now it was just a matter of passing down the necessary props to <strong>Circles &gt; Circle</strong> component and the refactor would be complete.</p><h3>The Map Component</h3><p>Once the Circles component was imported into Map it required the same conditional logic to render only when the data was present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZGOTL51GXZ3ekDg0CPIFA.png" /><figcaption>Image by author</figcaption></figure><h3>Conclusion</h3><p>I have to say that I prefer this approach over using D3 to render the circles. I suppose it’s because I’ve been working so heavily with React these days that I wholeheartedly believe it should manage the DOM whenever possible, which is almost always.</p><p>I also discovered <strong>React-Spring</strong> transitions in the process, and I’m super excited to incorporate the library into future projects.</p><p>Here is the<a href="https://codesandbox.io/s/d3-streetball-mecca-react-renders-map-circles-medium-j8v9q?file=/src/components/App/index.js"> CodeSandbox solution</a> that includes both refactors. All you need to do is go into the App component and adjust the comments to display the one you want to test.</p><p>As always, I’d love to hear any feedback/suggestions regarding the code so feel free to reach out with any thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7746600502" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/react-d3-rendering-circles-on-a-map-b7746600502">React &amp; D3: Rendering Circles On A Map</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The useD3 Custom Hook]]></title>
            <link>https://medium.com/swlh/the-used3-custom-hook-889ddbd30f18?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/889ddbd30f18</guid>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 21:36:28 GMT</pubDate>
            <atom:updated>2020-11-28T15:42:36.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>React &amp; D3: Experimenting With The useD3 Custom Hook</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDt7z-D46LvSAkLk0YQ3oA.png" /></figure><p>As of late, all my attention has been focused on working through a full refactor of Streetball Mecca from the original<a href="https://codepen.io/jkeohan/project/full/ZvKkKE"> D3 only version</a> to the newer<a href="https://vdsff.csb.app/"> React &amp; D3 version</a>. In the process, I’ve come across quite a few articles that discuss how to incorporate D3 into React, one of which included a custom <strong>useD3 hook</strong> and so I decided to perform one last refactor to the map and add the new hook to the mix.</p><p>In my previous article,<a href="https://jkeohan.medium.com/react-d3-rendering-a-map-5e006b2f4895"> React &amp; D3: Rendering A Map</a>, I discussed two approaches for incorporating D3 code into React. The initial approach, <strong>D3 within React</strong>,<strong> </strong>provides D3 with as much control as possible in rendering the data, but still requires the help of React’s <strong>useRef </strong>and <strong>useEffect</strong> hooks.</p><p>The second approach, <strong>D3 for the math and React for the DOM</strong>, gives React more control and calls upon D3’s specific helper functions. In the case of the map, it was <strong>d3.geoMercator </strong>for the projection and<strong> d3.geoPath </strong>for drawing the paths. I also decided to include <strong>d3.scaleOrdinal() </strong>to provide the mapping of boroughs and their assigned colors. In the end a simple object that mapped borough names as keys to corresponding colors would have sufficed, but I miss working with D3 scales, and wanted to keep that skillset sharp.</p><p>Both solutions rendered the following map, including the circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0RA8idz87TW2vbRcR_hCg.png" /></figure><p>Neither is better or worse for this type of visualization and for someone that works with React it’s hard not to want to coerce the code into React, allowing it to manage state, render the DOM, and update accordingly. All the while forcing D3 to take a back seat. However, for those well versed in D3 yet new to React they must first overcome the new learning curve.</p><h3>The useD3 Custom Hook</h3><p>The article I came across was<a href="https://www.pluralsight.com/guides/using-d3.js-inside-a-react-app"> “Using D3.js Inside a React App” by Benny Au</a>. In it, he creates a custom <strong>useD3</strong> hook that renders a vertical bar chart with x/y axes. Since the hook seemed to follow the <strong>D3 within React</strong> approach, I decided to refactor that solution and see how it might improve the existing codebase.</p><p>I decided to only render the Map using the hook and keep the existing useEffect to render the circles. My goal was to see how to work with the new hook and then to decide if it was worth the time to do any additional refactoring .</p><p>Since coding is a process and as one continues to explore other possibilities they may come to see their code in a new light. I also saw this as an opportunity to document what I learned along the way.</p><h4>The Existing <strong>D3 within React Code</strong></h4><p>Since the <strong>useD3 hook </strong>article fell in line with the <strong>D3 within React</strong> approach, I refactored that solution rendering both the Map and Circles. I’ve collapsed the code for both <strong>renderMap </strong>and <strong>renderParks</strong> for the time being.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlDsn9kSrUt3_QFOV3yh8g.png" /></figure><p>The things to highlight here, relevant to incorporating the <strong>useD3</strong> hook, are the <strong>svgRef </strong>and u<strong>seEffect</strong>, both of which will be migrated into the <strong>useD3</strong> hook. The <strong>renderMap</strong> function will basically remain as is with only a few small changes.</p><h4>Setting Up The Hook</h4><p>The first step in the refactor was to create and import the hook. I created a <strong>useD3.js</strong> file and copied/pasted the existing code right from the article. I also decided not to make any edits to the <strong>useD3</strong> code as I wanted to test it’s its reusability. If it could render the map, then it should be able to render the circles and bar chart somewhere down the line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*iRGkl7ly6umxb3l9CbCulQ.png" /></figure><h4>Inside The Hook</h4><p>As we can see a new <strong>ref </strong>is being created, which also becomes the return value of the function. <strong>useEffect </strong>is being used to call the function used to render the chart and does so based any changes to its dependency. One change that will require a small refactor in <strong>renderMap</strong> is that <strong>renderChartFn</strong> now passes the current <strong>svgRef </strong>reference as <strong>d3.select(ref.current).</strong></p><h4>Using The useD3 Hook</h4><p>So in order to keep as much of my code intact, I assigned the existing <strong>svgRef </strong>the return value from the <strong>useD3</strong> hook and passed it the <strong>renderMap </strong>function<strong> </strong>and <strong>[data.length] </strong>as the dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*bCu2Y-iATAGG1w1c6hZOfg.png" /></figure><p>I then needed to make a few edits to the <strong>renderMap</strong> function. This included the following:</p><ul><li>converting the <strong>renderMap</strong> function from an expression to a declaration as it’s now being called before it’s initialized</li><li>replacing the existing params with <strong>svg</strong> as the <strong>useD3</strong> hook passes <strong>d3.select(ref.current) </strong>to the callback function</li><li>replacing <strong>d3.select </strong>to reference the <strong>svg </strong>param, which will be a d3 reference to the to existing svg (<strong>d3.select(ref.current))</strong></li><li>adding conditional logic <strong>(if (data[0))</strong> to run only when the data exists</li><li>update d3 to reference the features array during the data binding <strong>data(data[0].features)</strong></li></ul><p>Here is what the code looked like after making those few edits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*fjn7Jn5UgV3WAJKz5rV1lQ.png" /></figure><h4>Wrapping My Head Around It</h4><p>The initial setup required a little troubleshooting as things didn’t fall right into place the first time around. As I was working through the errors I meticulously placed console logs, as I always do, in order to validate my assumptions but also realized they helped visualize the flow of execution. I’ll talk about this shortly.</p><p>Although I removed the console logs from the previous code snippets, I’ve added them back in to walk through <strong>what</strong> gets executed and <strong>when</strong>. I’ve recently gotten into the habit of adding descriptive text in my logs which takes the pattern of:</p><p><strong>Component or Function Name — where it’s located — the variable(s) it’s outputting.</strong></p><p>I can’t stress enough how this has helped me work through errors and even provided a reference to where I need to go back and comment out the console logs once the issue has been resolved.</p><h4>Flow Of Execution</h4><p>Anyone new to React may not yet understand the flow of execution in a component including initializing and updating state, rendering the DOM, and then of course the useEffect lifecycle methods. Hopefully this walkthrough might help explain things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PIhqJnG8LB4IHqaoTChjA.png" /></figure><p>The first console log shows the current state of the data that is initialized by the u<strong>seDataApi</strong> hook, which happens before the <strong>useD3 </strong>hook is instantiated. We can see that it contains no data as of yet and is an empty array.</p><p><strong>Map — before useD3- data []</strong></p><p>This is followed by a console log placed inside the hook just before useEffect. The output is that of the current state of the <strong>ref</strong>, which is <strong>undefined</strong>, and the dependency value which is [0].</p><p><strong>useD3(before useEffect) — ref, dependencies {current: undefined} [0]</strong></p><p>The reason the ref is undefined is because React has yet to return any JSX, which is when it binds the <strong>svgRef</strong> to the actual <strong>svg </strong>element. The dependency is [0] because it is passed <strong>data.length, </strong>which is empty.</p><p>The next output is just before Map’s return statement. I added this here to confirm the flow and to validate that <strong>useD3’s useEffect </strong>hasn’t run yet, and will not do so until after the Map component returns JSX.</p><p><strong>Map — before return — data []</strong></p><p>Now, as expected, once Map calls the return statement only then is the <strong>useEffect</strong> called.</p><p><strong>useD3(after useEffect) — ref — dependencies {current: svg#boroughs-map}[0]</strong></p><p>Now that <strong>useEffect</strong> is called it runs its codeblock calling <strong>renderChartFn</strong>, which is technically the <strong>renderMap</strong> function. Inside of that function I placed another console log. Here we can see that there is still no data as of yet which is why I needed to include the conditional logic <strong>if(data[0]).</strong></p><p>The useEffect was configured to run on the initial load (<strong>componentDidMount</strong>) and during any updates to its dependencies (<strong>componentDidUpdate</strong>), but the code would break as there was no data to bind to using <strong>d3.data.</strong></p><p><strong>Map — inside useD3 CB — svg Selection {_groups: Array(1), _parents: Array(1)} []</strong></p><p>Once state has been updated via the <strong>useDataApi</strong> hook, the component re-renders and the entire cycle repeats itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVax-OZaID4IiOsc2iDbLw.png" /></figure><p>As we can see data now exists and the dependency has been updated from <strong>[0] =&gt; [1] </strong>causing useEffect to execute its codeblock.</p><h3>Conclusion</h3><p>Although the useD3 hook is useful I would need to work out additional logic on how I might use it to render the circles as well considering a separate useEffect is currently being used to do so which has a separate dependency.</p><h4>Usefulness</h4><p>I think the hook does a good job in migrating some code out of the component and thus cleaning it up a bit. It’s also reusable, which I haven’t yet tested but will do so shortly enough.</p><h4>Performance</h4><p>One thing that I did notice was that once the <strong>useD3</strong> hook was in use the circles lost their animation which is an aesthetic I’d like to keep. When I had originally refactored the circles from <strong>D3 within React</strong> to <strong>D3(math)/React(DOM)</strong> I did need to leverage React-Spring to perform the animation. My guess is that this current issue is related the React rendering process.</p><p>Anyway, here is the <a href="https://codesandbox.io/s/d3-streetball-mecca-mapparks-custom-d3-hook-medium-yvxm6">CodeSandbox solution</a> that includes all 3 refactors. All you need to do is go into App and comment in the one you want to test. As always I’d love to hear any feedback/suggestions regarding the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=889ddbd30f18" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-used3-custom-hook-889ddbd30f18">The useD3 Custom Hook</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React & D3: Rendering A Map]]></title>
            <link>https://levelup.gitconnected.com/react-d3-rendering-a-map-5e006b2f4895?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e006b2f4895</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 17:20:12 GMT</pubDate>
            <atom:updated>2020-11-25T14:18:13.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBNie05HRtNQh8uhi2d2RA.png" /></figure><p>Ever since I discovered D3 I was immediately fascinated with all its capabilities. It was built as a low level JavaScript data visualization library which meant you were only limited by your imagination as to what you could build, render, and interact with on the screen. It’s also one of the most widely used JavaScript data viz libraries with over <a href="https://github.com/d3/d3">95k stars on Github.</a></p><p>I studied it heavily for several years after graduating the WDI (Web Development Immersive) program at GA back in 2015 and even ran a weekly meetup at their NYC campus back in 2018.</p><p>In 2016 I was hired by GA to teach my very first WDI program and needed to learn React pronto as the team I was working with decided to incorporate it into our curriculum. The more I learned about React, the more intrigued I was and because the demand to master all the content, D3 was put on hold.</p><p>That was until the last few months when I decided to finally jump back into D3 and decided to refactor a previous D3 dashboard project I built called <a href="https://codepen.io/jkeohan/project/full/ZvKkKE">Streetball Mecca</a>.</p><p>Much of this refactoring involved replacing D3 to create and/or update/delete elements and hand that over to React. One of Reacts strengths is managing state so initially chose <strong>useState</strong> but then refactored it over to <strong>useReducer</strong> as it is a much better choice for managing state and complex business logic. Lastly I broke the design into smaller and smaller components for manageability.</p><h4><strong>Integrating D3 and React</strong></h4><p>Integrating React and D3 requires making the decision on how much control to give, or take away from, D3 as both D3 and React want full control over the DOM.</p><p>Here are the 3 basic approaches you should consider:</p><ul><li>D3 within React — React renders an svg and D3 does all the rest</li><li>D3 for it’s unique methods (scales, axes, projections, etc..) and React to manage state and update the DOM</li><li>Using a 3rd party React/D3 library such as high level one like <a href="https://nivo.rocks/#/">Nivo</a> or a low level like <a href="https://vx-demo.now.sh/https://vx-demo.now.sh/">VX</a>.</li></ul><p>Each approach has their advantages/disadvantages and in the end it comes down to which technology you are most proficient, D3 or React.</p><h4>D3 within React</h4><p>At first, I took the <strong>D3 within React</strong> approach as it was the easiest way to migrate the existing codebase. At this point I was well versed in both libraries but combining the two was a new adventure and required a bit of research and many trials and tribulations.</p><p>After I reviewed the original design I decided to limit D3 to just the <strong>map, circles </strong>and <strong>bar chart (including the x axis) </strong>and allow React to render all other elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-C6lKlZ5uBI5Y5kwqbaN4A.png" /></figure><h4>The D3 Map Component</h4><p>For the Map, I mostly copied over the <strong>renderChart</strong> function and created a <strong>ref(erence) </strong>to the svg. Ref’s in React are just a reference which can be to a DOM node or JavaScript value. In the use case of the svg I equate it to using <strong>document.querySelector </strong>grab<strong> </strong>a DOM element. On the other hand assigning a ref to a JS value is done so to maintain that value through one or more state changes.</p><p>The ref is an object that stores the value it’s assigned to its <strong>current </strong>key which would then be passed to the <strong>d3.select()</strong> in order to grab that DOM element.</p><p>Here the ref is instantiated using the <strong>useRef </strong>hook and then the <strong>svgRef</strong> is assigned to the svg element using <strong>ref={svgRef}.</strong></p><pre>import React from &#39;react&#39;<br>import * as d3 from &#39;d3&#39;</pre><pre>const Map = (props) =&gt; {</pre><pre>   //////////////////////////////////////////////////////<br>   // REFs<br>   //////////////////////////////////////////////////////</pre><pre>   const svgRef = useRef();  </pre><pre>   ////////////////////////////////////////////////////// <br>   // RENDER THE CHART USING D3<br>   //////////////////////////////////////////////////////   </pre><pre>   const renderChart = (nyc, path) =&gt; {<br>     d3.select(svgRef.current)<br>      //...additional d3 code...<br>   };</pre><pre>    ////////////////////////////////////////////////////// <br>    // RENDER THE SVG<br>    //////////////////////////////////////////////////////</pre><pre>   return(    <br>     &lt;svg id=&quot;boroughs-map&quot; ref={svgRef}&gt;&lt;/svg&gt;<br>   )<br>}</pre><p>Another ref was then instantiated for the D3 projection, in this case <strong>d3.geoMercator().</strong> In this instance it’s being used as <strong>instance variable</strong> within the functional component as this value will be referenced by both the map and the circles at different times during the components lifecycle.</p><pre>//////////////////////////////////////////////////////<br>// REFs<br>//////////////////////////////////////////////////////<br>const svgRef = useRef()<br>const projRef = useRef(d3.geoMercator()<br>   .center([-73.93, 40.72]).scale(57500));</pre><p><strong>useEffect </strong>is<strong> </strong>then used to grab the height/width of the svg which is used to center the projection. <strong>useEffect </strong>is being implemented here as a <strong>componentDidUpdate </strong>lifecycle method that has a single <strong>dependency. </strong>Any change in value to the dependency will cause the <strong>useEffect </strong>method<strong> </strong>to rerun.</p><pre>//////////////////////////////////////////////////////<br>// USEEFFECT AS COMPONENTDIDUPDATE WITH DEPENDENCY<br>//////////////////////////////////////////////////////<br>useEffect(() =&gt; {</pre><pre>  const height = svgRef.current.clientHeight<br>  const width = svgRef.current.clientWidth</pre><pre>  projRef.current.translate([width  / 2, height  / 2 ]);</pre><pre>}, [data])</pre><p>The projection is D3 specific and it defines how the map will be displayed. D3 comes with various projections with <strong>.geoMercator() </strong>being the most commonly used. In this particular use case it needs to be centered using <strong>translate</strong> which requires the height/width values.</p><pre>//////////////////////////////////////////////////////<br>// USEEFFECT AS COMPONENTDIDUPDATE WITH DEPENDENCY<br>//////////////////////////////////////////////////////<br>useEffect(() =&gt; {</pre><pre>   const height = svgRef.current.clientHeight<br>   const width = svgRef.current.clientWidth</pre><pre>   projRef.current.translate([width  / 2, height  / 2 ]);</pre><pre>}, [data])</pre><p>The projection is then passed to <strong>d3.geoPath() </strong>to draw the actual svg paths that define the shapes for the boroughs in the map. I’ve also included an <strong>if </strong>statement that will pass the map data and path to renderChart only when there is actual data to render.</p><pre>//////////////////////////////////////////////////////<br>// USEEFFECT AS COMPONENTDIDUPDATE WITH DEPENDENCY<br>//////////////////////////////////////////////////////<br>useEffect(() =&gt; {</pre><pre>   const height = svgRef.current.clientHeight<br>   const width = svgRef.current.clientWidth</pre><pre>   projRef.current.translate([width  / 2, height  / 2 ]);</pre><pre>   const path = d3.geoPath().projection(projeRef.current)</pre><pre>   if (data.length) {<br>     renderChart(data[0], path)<br>   }</pre><pre>}, [data])</pre><p>Here is all the code thus far.</p><pre>//////////////////////////////////////////////////////<br>// REFs<br>//////////////////////////////////////////////////////<br>const svgRef = useRef()<br>const projRef = useRef(d3.geoMercator()<br>   .center([-73.93, 40.72]).scale(57500));</pre><pre>//////////////////////////////////////////////////////<br>// USEEFFECT AS COMPONENTDIDUPDATE WITH DEPENDENCY<br>//////////////////////////////////////////////////////<br>useEffect(() =&gt; {</pre><pre>   const height = svgRef.current.clientHeight<br>   const width = svgRef.current.clientWidth</pre><pre>    projRef.current.translate([width  / 2, height  / 2 ]);</pre><pre>   const path = d3.geoPath().projection(projeRef.current)</pre><pre>   if (data.length) {<br>     renderChart(data[0].features, path)<br>   }</pre><pre>}, [data])</pre><p>As for the <strong>renderChart </strong>function, it’s only 8 lines of actual code and is all D3:</p><ul><li>data binding — <strong>.data(data)</strong></li><li>data entering — <strong>.enter()</strong></li><li>appending data <strong>— .append(‘path’)</strong></li><li>appending attributes — .<strong>attr(‘d’, path)</strong></li><li>appending styles — .<strong>style(‘fill’, (d) =&gt; boroughLegend(d.properties.borough))</strong></li></ul><pre>const renderChart = (data, path) =&gt; {<br>   d3.select(svgRef.current).selectAll(&#39;path&#39;)<br>     .data(data).enter().append(&#39;path&#39;)<br>     .attr(&#39;class&#39;, (d) =&gt; d.properties.name)<br>     .attr(&#39;d&#39;, path)<br>     .style(‘fill’, (d) =&gt; boroughLegend(d.properties.borough))<br>};</pre><h4>D3 for the math and React for the DOM</h4><p>Although this worked to render the map I knew that some portion of the D3 code could be supplanted with React. So the question was what elements could be easily rendered by React and the answer was quite clear, the <strong>path </strong>elements.</p><p>So the following refactoring would be required:</p><ul><li>create a new ref to store the value of d3.geoPath() — this was because I decided to move the conditional logic from useEffect to the return statement</li><li>update useEffect to update the new pro</li><li>use .map() to iterate over the data and create the path elements and assign them the needed properties</li><li>use conditional logic inside in the components return statement to render the paths if there was data</li></ul><p>Adding the new ref required little effort.</p><pre>//////////////////////////////////////////////////////<br>// REFs<br>//////////////////////////////////////////////////////<br>const svgRef = useRef()<br>const projRef = useRef(d3.geoMercator()<br>   .center([-73.93, 40.72]).scale(57500));<br>const pathRef = useRef()</pre><p>Updating the <strong>pathRef </strong>in useEffect also was no big deal. I also cleaned up <strong>useEffect</strong> a bit by removing the conditional logic.</p><pre>//////////////////////////////////////////////////////<br>// USEEFFECT AS COMPONENTDIDUPDATE WITH DEPENDENCY<br>//////////////////////////////////////////////////////<br>useEffect(() =&gt; {</pre><pre>  const height = svgRef.current.clientHeight<br>  const width = svgRef.current.clientWidth</pre><pre>   projRef.current.translate([width  / 2, height  / 2 ]);</pre><pre>   pathRef.current = d3.geoPath().projection(projRef.current);</pre><pre>}, [data])</pre><p><strong>renderChart()</strong> required the most effort but I wouldn’t even go that far. All it did was replace <strong>D3’s data binding</strong> and <strong>enter</strong> methods with mapping over the array, creating the paths and assigning the the properties.</p><pre>const renderChart = () =&gt; {<br>  return data[0].features.map((d,i) =&gt; {<br>    const featurePath = `${pathRef.current(d)}`<br>      return (<br>        &lt;path <br>          key={i} <br>          d={featurePath} <br>          className={d.properties.name}<br>          fill={boroughLegend(d.properties.borough)}<br>        /&gt;<br>       )<br>   })<br>};</pre><p>And the last step was to add the conditional logic to the Map components return statement.</p><pre>return (<br>  &lt;svg id=&quot;boroughs-map&quot; ref={svgRef}&gt;<br>    {data.length &amp;&amp; renderChart()}<br>  &lt;/svg&gt;<br>);</pre><h3><strong>Conclusion</strong></h3><p>I have to say that I prefer this approach over using D3 to render the map. I suppose it’s because I’ve been working so heavily with React these days that I believe it should manage the DOM whenever possible, which is almost always.</p><p>In a way, I’m almost sad to supplant D3 with React for this functionality, as I had grown accustomed to D3’s <strong>Data Binding</strong> and <strong>Enter/Update/Exit </strong>pattern and it was something I always made a point to teach in any intro to D3 class.</p><p>In truth, React seems better suited for rendering the elements and keeping track of any state changes via <strong>useState </strong>or <strong>useReducer. </strong>D3 is still powerful and efficient in its own right and offers many features not available in React so I’m glad I still get to incorporate it into this project.</p><p>Here is the<strong> </strong><a href="https://codesandbox.io/s/d3-streetball-mecca-map-only-rsqpv?file=/src/components/Map/indexV2.js"><strong>CodeSandbox</strong></a> for the map and circles and includes 2 files with the code for rendering the map via D3 and the refactor over to React. Give them both a test run and let me know if you see any additional room for improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*YKzKSwJE48WGND2fguKwwA.png" /></figure><p>I’ve also included the input and dropdown functionality for filtering the parks based on the chosen park or selected borough.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIVi9DglnwkQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIVi9DglnwkQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIVi9DglnwkQ%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/88005e25a090444ba3cb1f0addfe82a5/href">https://medium.com/media/88005e25a090444ba3cb1f0addfe82a5/href</a></iframe><p>I’m in the process of writing a followup article where I replace D3 for generating and animating the circles with a React Circle Component as well as incorporate <a href="https://www.react-spring.io/"><strong>React-Spring</strong></a><strong> </strong>for animating the circles.</p><p>If you are interested in reading more about this project, check out my previous article on<a href="https://jkeohan.medium.com/react-managing-complex-state-transitions-with-usereducer-e37536b12944"> React: Managing Complex State Transitions with useReducer</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e006b2f4895" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/react-d3-rendering-a-map-5e006b2f4895">React &amp; D3: Rendering A Map</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React: Managing Complex State Transitions With useReducer]]></title>
            <link>https://medium.com/swlh/react-managing-complex-state-transitions-with-usereducer-e37536b12944?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37536b12944</guid>
            <category><![CDATA[usereducer]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 01:08:14 GMT</pubDate>
            <atom:updated>2021-09-01T23:25:51.371Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*kBcSU8c9DJ77N1Hgv3D4dg.png" /></figure><h3>The Backstory</h3><p>I’ve recently started working on refactoring a D3 project that I built earlier this year called<a href="https://codepen.io/jkeohan/project/full/ZvKkKE"> Streetball Mecca</a>. The project itself is a rebuild of a <a href="https://interworks.com/blog/dsiegel/2018/02/02/streetball-mecca-mapping-nyc-basketball-courts-tableau/">Tableau dashboard</a> created by David Siegel but with a few small design changes. I’ve always struggled with dashboard design so I often seek out existing projects to rebuild.</p><p>My version of the project was done solely in D3 and, although I was quite proud of the original rebuild, I’ve come to the conclusion that React would have been a much better choice to organize the project, as well as, manage much of the business logic using the <strong>useReducer </strong>hook.</p><p>Over the last year I’ve worked extensively with hooks and expanding my knowledge beyond useState to include: useReducer, useContext, useRef, useMemo. I’ve also taught a few intro to Redux classes so I understand the true power and benefit of incorporating some logic for state management.</p><h3>The Existing D3 Codebase</h3><p>My goal now is to take all that knowledge and refactor the D3 project within the framework of React and limit D3 to only the map and bar chart. Even then I’m going to render as many of those elements via React as possible.</p><p>The original D3 code was the following collection of files. All the files had one or more functions, some of which needed to be loaded first so they would be available in the scope for functions loaded later on.</p><p>Although the naming convention of the files helped direct my attention, when it came time to understand what I had done almost a year ago there were times I found myself searching for logic not quite knowing where I had placed it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*4bx_fvl6qvaUefLKQqaB_Q.png" /></figure><p>I won’t go any further into the code but will reiterate that almost every UI element and interaction was created via D3 in these files. Here is the <a href="https://codepen.io/jkeohan/project/editor/ZvKkKE#">link to the project in codepen</a>.</p><h3>The Initial Refactor</h3><p>I did little planning and just jumped right in and started to code. I thought to myself that I’d build out the components one at a time and implement the logic as needed using <strong>useState</strong> to manage state.</p><p>Well, as you can imagine, that was not the best decision and I found myself with dispersed logic in several hander functions.</p><p>Here is what the original logic looked like in App. At a quick glance, someone who understands React will surely be able to make sense of the logic and this approach would continue to work regardless of how much more functionality was added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ELbhHjjVP1vezHk93Bh8Gw.png" /></figure><p>However as I started to incorporate more functionality, this approach started to include more and more helper functions which needed to be passed to the hierarchy and started to appear bloated.</p><p>I knew there was a better way to manage state and the business logic and kicked myself in the ass for not having invested more time choosing <strong>useReducer </strong>to<strong> </strong>structure the code.</p><h3>The Second Refactor</h3><p>So now it was time for the second refactor. Once this portion was completed I was able to truly appreciate the power of<strong> useReducer</strong> and its ability to structure and organize the code into something that seemed more cohesive and intuitive to understand.</p><p>Using <strong>actions</strong> that are then <strong>dispatched </strong>to the <strong>reducer </strong>provided a central place to manage the state and business logic of the application.</p><p>Here is the <strong>parkReducer </strong>and<strong> </strong>some<strong> </strong>of the<strong> </strong>supporting helper functions<strong>. </strong>One quick glance over the code and you can clearly see the <strong>actions</strong> which, by convention, are written in uppercase. These actions define the business logic and are then dispatched by the child components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*FbydPopSDJt4OfTZpOJ72g.png" /></figure><p>The App codebase was then significantly reduced and needed to only import the reducer, instantiate a new instance, and pass it an initial state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Xm2mh6iU1_a5wC8ifDvD-g.png" /></figure><p>The reducer takes in the initial state and returns it as <strong>parkData. </strong>It also returns a <strong>dispatch</strong> function, which is used to pass actions to the reducer.</p><p><strong>Actions</strong> tend to be objects and are assigned a key called <strong>type</strong>, also by convention, which contains the action to be performed. It also may carry a <strong>payload</strong> if data needs to also be passed to the reducer.</p><p>In this case the payload is the data retrieved from the initial API call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*5h4ZquYg5qkljTtil9KtHQ.png" /></figure><p>The <strong>action </strong>once received is evaluated using a <strong>switch </strong>statement, which is another convention used for writing the conditional logic in a reducer. It then returns a new version of state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGauXZMu2MePHdnfOLwBOA.png" /></figure><p>One action that didn’t need a payload was the reset button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*hkLxnxI39YiuAuWs4rcsyA.png" /></figure><h3>Conclusion</h3><p>Although I’m not yet finished with the refactor, I believe making the switch to <strong>useReducer</strong> was the right choice. I’ve also contemplated incorporating <strong>useContext, </strong>however,<strong> </strong>I’m just not finding a solid use case as the React hierarchy is only a few components deep and prop drilling seems to work just fine. I’m also only passing down a single <strong>dispatch </strong>function which only forces me to define one additional prop to pass from App.</p><p>Here is the <a href="https://codesandbox.io/s/streetball-mecca-iterative-solution-nt8se?file=/src/hooks/useDataApi.js">CodeSandbox</a> of the latest iteration of the project in case you want to give it a closer look.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37536b12944" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/react-managing-complex-state-transitions-with-usereducer-e37536b12944">React: Managing Complex State Transitions With useReducer</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Responsive Slider]]></title>
            <link>https://itnext.io/react-responsive-slider-2ed4b07867b3?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ed4b07867b3</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Thu, 19 Dec 2019 10:41:18 GMT</pubDate>
            <atom:updated>2019-12-20T21:00:55.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5x1AzCf89WWtle_VsTy0g.png" /></figure><h4>Introduction</h4><p>In my last article <a href="https://medium.com/@jkeohan/3-ways-to-implement-responsive-design-in-your-react-app-bcb6ee7eb424">3 Ways To Implement Responsive Design In Your React App</a> I discussed several ways to implement responsive design in a React app. Inspiration for that app was <a href="https://mars.nasa.gov/">mars.nasa.gov</a>, and in this article I continue to rebuild additional portions of the site with the main focus on implementing the bottom slider functionality in the header section on the main page.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fspanishsilkycassowary&amp;url=https%3A%2F%2Fgfycat.com%2Fspanishsilkycassowary&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FSpanishSilkyCassowary-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1280" height="616" frameborder="0" scrolling="no"><a href="https://medium.com/media/205623d7b116ec7dcd18d226693f2008/href">https://medium.com/media/205623d7b116ec7dcd18d226693f2008/href</a></iframe><p>Here is a deployed version and the codesandbox:</p><p>App: <a href="https://02nz9.csb.app/">https://02nz9.csb.app/</a></p><p>Codesandbox: <a href="https://codesandbox.io/s/mars-slider-demo-02nz9">https://codesandbox.io/s/mars-slider-demo-02nz9</a></p><h4>The “BottomSlider” Component</h4><p>Creating a Component to encompass all the elements and functionality for the slider seems the most practical approach, especially since I was considering including it other apps I’d like to build.</p><p>As I’m always looking to keep myself up to date with the latest and greatest React has to offer I’ve decided to incorporate Hooks. I’ve included <strong>useReducer </strong>to manage <strong>PREV/NEXT/RESET</strong> states, <strong>useEffect</strong> to initiate the <strong>RESET</strong> state when the window.innerWidth value changes, and <strong>useRef</strong> to grab a reference the .slick-track element that holds the sliders.</p><p>Here is the basic structure. Additional content such as the reducer’s inner workings or the sliderController object will be explained later in the article.</p><pre>import React, { useReducer, useEffect, useRef } from  &quot;react&quot;;<br>import &#39;./BottomSlider.css&#39;</pre><pre>function BottomSlider() {</pre><pre> // useRef<br> const slideTrackRef = useRef()</pre><pre> // useReducer <br> const reducer = (state, action) =&gt; {<br>  ...rest of code<br> }<br> const [sliders, dispatch] = useReducer(reducer, sliderController)</pre><pre> // useEffect<br> useEffect( () =&gt; {<br>   dispatch(&#39;RESET&#39;)<br> }, [windowWidth()])</pre><pre> ...rest of code<br>}</pre><h4>The Content</h4><p>The content is an array of objects that I’ve mirrored from the mars site. For the sake of organization I’ve placed the content into its own file called <strong>BottomSliderData.js </strong>and imported it into the main <strong>BottomSlider.js </strong>Component.</p><pre>// BottomSlider.js Component<br>import sliderContent from &#39;./BottomSliderData&#39;</pre><pre>// BottomSliderData.js<br>   export default[{<br>     title: &#39;Curiosity&#39;,<br>     value: &#39;2440 SOLS ON MARS&#39;<br>   },...additional objects]</pre><h4>Render The Content</h4><p>As I like to extrapolate any looping constructs(.map) from the Components <strong>return </strong>statement<strong>, </strong>I opted to create a variable called <strong>renderSlickTrackSlides</strong> that stores the results of mapping over the <strong>sliderContent </strong>array and creating the individual slider elements.</p><pre>const renderSlickTrackSlides = sliderContent.map( (d,i) =&gt; (<br>  &lt;article className=&quot;slide&quot; key={i}&gt;<br>   &lt;div className=&quot;image_and_description_container&quot;&gt;<br>    &lt;div className=&quot;readout&quot;&gt;<br>     &lt;div className=&quot;title&quot;&gt;{d.title}&lt;/div&gt;<br>     &lt;div className=&quot;value&quot;&gt;{d.value}&lt;/div&gt;<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;span className=&quot;circle_plus&quot;&gt;&lt;/span&gt;<br>  &lt;/article&gt;<br>))</pre><p>The .<strong>slick-track</strong> will render those elements and has also been assigned the <strong>slideTrackRef </strong>reference<strong> </strong>that was defined earlier.</p><pre>&lt;div className=&quot;slick-track&quot; ref={slideTrackRef}&gt;  <br>   {renderSlickTracks}<br>&lt;/div&gt;</pre><p>Buttons have been placed on either side of the <strong>.slick-list </strong>element and have been assigned background images that were pulled directly from the mars site. Thank you NASA!</p><pre>&lt;section className=&quot;dashboard&quot;&gt;<br> &lt;div className=&quot;slide_container&quot;&gt;<br>  &lt;button className=&quot;slick-prev&quot;&gt;&lt;/button&gt;<br>  &lt;div className=&quot;slick-list&quot;&gt;<br>   &lt;div className=&quot;slick-track&quot; ref={slideTrackRef} &gt;  <br>    {renderSlickTracks}<br>   &lt;/div&gt;<br>   &lt;button className=&quot;slick-next&quot;&lt;/button&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/section&gt;</pre><h4>Adding Event Listeners</h4><p>Click events were added to both the <strong>.slick-prev</strong> and <strong>.slick-next </strong>elements and are configured to call the useReducer’s <strong>dispatch</strong> method passing it one of two values: <strong>“PREV” </strong>or <strong>“NEXT”</strong>.</p><pre>&lt;section className=&quot;dashboard&quot;&gt;<br> &lt;div className=&quot;slide_container&quot;&gt;<br>  &lt;button className=&quot;slick-prev&quot; onClick={() =&gt; dispatch(&#39;PREV&#39;)}&gt;<br>  &lt;/button&gt;<br>   ...slick-list<br>  &lt;button className=&quot;slick-next&quot; onClick={() =&gt; dispatch(&#39;NEXT&#39;)}&gt;<br>  &lt;/button&gt;<br> &lt;/div&gt;<br>&lt;/section&gt;</pre><h4>Showing The Right Number Of Slides</h4><p>Responsive design has always taken precedence in this project and so I’ve created the <strong>windowWidth()</strong> function that returns the current value of <strong>window.innerWidth</strong>.</p><p>The <strong>numOfVisibleSlides()</strong> function calls windowWidth() and returns the value equal to the number of slides currently being shown based on a specific breakpoint.</p><pre>const windowWidth = () =&gt; {<br>  return window.innerWidth;<br>};</pre><pre>const numOfVisibleSides = () =&gt; {<br>  switch (true) {<br>   case windowWidth() &lt;= 767 :<br>    return 1<br>   case windowWidth() &lt;= 1023 :<br>    return 2<br>   default :<br>    return 3<br>  }<br>}</pre><p>A<strong> sliderController</strong> object was created to keep track of the following properties:</p><ul><li><strong>numOfVisibleSlides:</strong> the number of slides visible at the current window width</li><li><strong>numOfSliders:</strong> the current length of the sliderContent array</li><li><strong>translateValue:</strong> the sliders’ current transition value</li></ul><pre>const sliderController = {<br> numOfVisibleSlides: numOfVisibleSldies(),<br> numOfSliders: sliderContent.length,<br> translateValue: 0<br>}</pre><h4>UseReducer To Manage The NEXT &amp; PREV States</h4><p>The <strong>useReducer</strong> Hook is a great choice for more complex state management. If you’re new to useReducer then the additional code overhead might seem much at first, however, it’s a great tool for managing your state and application logic, thereby making it a bit more intuitive and readable.</p><p>useReducer is passed a <strong>reducer</strong> function which is bound to the <strong>dispatch</strong> method and the <strong>sliderController </strong>array bound to the<strong> sliders </strong>variable.</p><pre>const [sliders, dispatch] = useReducer(reducer, sliderController)</pre><p>The <strong>“NEXT”</strong> and <strong>“PREV”</strong> actions are tied to event listeners currently assigned to the forward/back buttons. <strong>“RESET”</strong> was added to reset the useReducers state thereby transitioning the slider back to its original placement when the window.innerWidth value changes.</p><pre>function reducer(state,action) {<br> switch(action) {<br>  case &#39;RESET&#39; :<br>    return sliderController<br>  case &#39;PREV&#39; :<br>   return handlePrev(state)<br>  case &#39;NEXT&#39; :<br>   return handleNext(state)<br>  default :<br>   return state<br> }<br>}</pre><p>useReducer leverages switch statements as it’s more intuitive than trying to read a series of if/else if/else statements.</p><h4>Moving Forward</h4><p>The<strong> handleNext() </strong>function needs to do the following:</p><ul><li>Calculate the distance to transition left along the horizontal axis</li><li>Apply the transition and display the next slide in the sequence</li><li>Prevent further transitions once the the max limit of slides is reached</li><li>Return a new version of state with those changes</li></ul><pre>function handleNext({numOfVisibleSlides, numOfSlides, translateValue}) {</pre><pre>  if (numOfVisibleSlides &gt;= numOfSlides) {<br>    return { numOfVisibleSlides, numOfSlides, translateValue }<br>   }</pre><pre>  let value = numOfVisibleSides()</pre><pre>  translateValue += -(slideTrackWidth() / value);</pre><pre>  return {<br>   numOfVisibleSlides: numOfVisibleSlides += 1,<br>   numOfSlides,<br>   translateValue<br>  }<br>}</pre><h4>Moving Backwards</h4><p>The<strong> handlePrev() </strong>function needs to do the following:</p><ul><li>Calculate the distance to transition right along the horizontal axis</li><li>Apply the transition and display the next slide in the sequence</li><li>Prevent further transitions once the base limit of slides is reached</li><li>Return a new version of state with those changes</li></ul><pre>function handlePrev({numOfVisibleSlides, numOfSlides, translateValue}) {</pre><pre> if (numOfVisibleSlides &lt;= numOfVisibleSides()) {<br>  return { numOfVisibleSlides, numOfSlides, translateValue }<br> }</pre><pre> let value = numOfVisibleSides()</pre><pre> translateValue += slideTrackWidth() / value;</pre><pre> return {<br>  numOfVisibleSlides: numOfVisibleSlides -= 1,<br>  numOfSlides,<br>  translateValue<br> }<br>}</pre><p>Both functions call the <strong>slideTrackWidth</strong> function which returns the current width of <strong>.slick-track</strong>. Its width will change in response to window width.</p><pre>const slideTrackWidth = () =&gt; {<br> return slideTrackRef.current.clientWidth;<br>};</pre><h4>Conclusion</h4><p>After several refactors and a little bit of Hook magic, I’ve created a reusable and responsive Component.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ed4b07867b3" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/react-responsive-slider-2ed4b07867b3">React Responsive Slider</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways To Implement Responsive Design In Your React App]]></title>
            <link>https://itnext.io/3-ways-to-implement-responsive-design-in-your-react-app-bcb6ee7eb424?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcb6ee7eb424</guid>
            <category><![CDATA[responsive-web-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 00:37:37 GMT</pubDate>
            <atom:updated>2022-03-05T22:18:40.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYGqYfPIt-FIVp2JGUgc0g.png" /></figure><h4><strong>React — The Game Changer</strong></h4><p>React has truly been a game changer in how we now approach developing front-end applications for the web. Components, right from their introduction, went against the “separation of concerns” rule of thumb, choosing to leverage JSX and bringing together HTML and JS in the same file. UI elements are now being rendered via their own Components with all the intent and purpose of reusability.</p><h4>Responsive Done Many Ways</h4><p>Responsive design was always a requirement and now that we’re building apps using the “mobile first” mindset, is even more important than ever.</p><p>Using the most basic approach, responsive design has been implemented using Media Queries, where a more experienced developer might opt to add event listeners that respond to the “resize” event and add/remove styles via JS. Even still, both novice and experienced developers alike might work with a front-end framework like Bootstrap or Materialize with predefined breakpoints and custom Components for making those changes.</p><h4><strong>React And Implementing Responsive Design</strong></h4><p>So let’s take a look at 3 different approaches to implementing responsive design in your next React app.</p><ol><li>Media Queries</li><li>Inline styles</li><li>Higher Order Components — (React-Socks)</li></ol><p><strong>The Process</strong></p><p>As we review the different ways to implement responsive design, I’ll focus on the following points which must be accomplished regardless of which approach you take.</p><ol><li>Tracking changes to the window size (width/height)</li><li>Add/Remove/Update the necessary DOM elements to reflect those changes</li></ol><p><strong>The Demo</strong></p><p>App: <a href="https://wpixk.csb.app/">https://wpixk.csb.app/</a></p><p><strong><em>Note:</em></strong> The above demo is using the Inline-Style approach</p><p>Although this site has many responsive features, for the purpose of this demo I will be focusing solely on the navigation menu and making the following changes:</p><p>Mobile: width &lt; 1024 — Removes the top navigation and shows the hamburger icon</p><p>Desktop: width &gt; 1023 — Shows the navigation elements and hides the hamburger icon</p><p>So let’s begin!</p><h4>Media Queries</h4><p>The power of CSS never ceases to amaze and inspire. I’ve seen countless CSS works of art on CodePen and on almost any given day I learn something new about CSS. So it goes without saying that the first approach to implementing responsive design is using Media Queries.</p><p>CodeSandbox: <a href="https://codesandbox.io/s/mars-media-queries-0wqnv">https://codesandbox.io/s/mars-media-queries-0wqnv</a></p><p><strong><em>Note:</em></strong> Media Queries were added to a separate <strong>responsive.css</strong> file</p><p><strong>Tracking Changes To The Window Size</strong></p><p>Changes to the window size are tracked using the <a href="https://www.w3schools.com/cssref/css3_pr_mediaquery.asp">CSS @media rule</a> and setting the min-width to 1024px. This essentially states that the rules defined here apply only when the window width is at a minumum of 1024ppx.</p><pre>@media only screen and (min-width: 1024px) {</pre><pre>}</pre><p><strong>Updating DOM Elements</strong></p><p>Within the media query rule, additional CSS rules are added that target specific DOM elements.</p><pre>@media only screen and (min-width: 1024px) {<br>  .container header .header-nav-area #nav_container  {<br>    display:flex;<br>  }<br>}</pre><p><strong>Pros/Cons</strong></p><p>Pros</p><ul><li>Relatively simple to apply</li><li>Anyone with basic CSS skills can create and implement Media Queries</li></ul><p>Cons</p><ul><li>React will render extra DOM elements, hidden by CSS, that are never used</li><li>CSS is external to the Component</li><li>An additional import needed for the CSS file</li></ul><h4>Inline Styles</h4><p>Anytime I teach intro Front-End Web Dev and the topic of inline styles I always say, emphatically, “Don’t do this”. I then continue to reinforce that styles should be defined via CSS. It’s not until we get to learn JS and/or jQuery that adding styles via .style or .css() do we break the rule.</p><p>CodeSandbox: <a href="https://codesandbox.io/s/mars-inline-styles-wpixk">https://codesandbox.io/s/mars-inline-styles-wpixk</a></p><p><strong><em>Note: </em></strong>Nav elements have been split off into their own Components and placed into a TopNav folder</p><p><strong>Tracking The Window Size</strong></p><p>Tracking changes to the window size requires that we add an event listener to the window object that listens for “resize” events. Once a “resize” event occurs, a callback function is called that retrieves the current width from the window object.</p><pre>window.addEventListener(“resize”, updateDimensions)</pre><pre>const updateDimensions = () =&gt; {<br>  const width = window.innerWidth<br>}</pre><p>Since Hooks are all the rage, let’s import and use <strong>useState </strong>to create a width variable and its supporting setWindowWidth() method, which will be used to update the width in the updateDimensions() function.</p><pre>import React, { useState } from &#39;react&#39;</pre><pre>function App() {<br>  const [width, setWindowWidth] = useState(0);</pre><pre>  const updateDimensions = () =&gt; {<br>    const width = window.innerWidth<br>    setWindowWidth(width)<br>  }</pre><pre>  //…rest of App.js below…<br>}</pre><p>Then we will create a supporting function that will be responsible for grabbing the window.innerWidth value and updating state:</p><p><strong>Adding The Event Listener</strong></p><p>The <strong>useEffect </strong>Hook must now be imported and used to do the following:</p><ol><li>Call updateDimensions to set the initial width to the current window size</li><li>Add the event listener when the Component mounts</li><li>Remove the event listener when the Component unmounts</li></ol><p>useEffect essentially replaces the class-based componentDidMount, componentDidUppdate, and componentWillUnmount lifecycle methods.</p><pre>import React, { useState, useEffect } from &#39;react&#39;</pre><pre>function App() {<br>  const [width, setWindowWidth] = useState(0)</pre><pre>   useEffect(() =&gt; { <br><br>     updateDimensions();<br><br>     window.addEventListener(“resize”, updateDimensions);</pre><pre>     return () =&gt; <br>       window.removeEventListener(“resize”,updateDimensions);</pre><pre>    }, [])</pre><pre>    const updateDimensions = () =&gt; {<br>      const width = window.innerWidth<br>      setWindowWidth(width)<br>    }</pre><pre>   //…rest of App.js below…<br>}</pre><p><strong>Updating The Elements</strong></p><p>I’ve opted to create an object that uses conditional logic to determine if any changes to width require showing/hiding the top navigation. This is then passed down as props to the <strong>Header</strong>.</p><pre>const responsive = {<br>  showTopNavMenu: width &gt; 1023<br>}</pre><pre>return (<br>  &lt;&gt;<br>    &lt;Header showTopNavMenu={responsive.showTopNavMenu}/&gt;<br>    &lt;Main /&gt;<br>  &lt;/&gt;<br>)</pre><p>The<strong> </strong>Header then works out its own logic to determine the exact CSS that will be used to show/hide specific DOM elements. In this case, the elements will either have their display property set to “flex” or “none”.</p><pre>const showNav= {<br>  display: showTopNavMenu ? &#39;flex&#39; : &#39;none&#39;<br>}</pre><pre>const showMenuIcon = {<br>  display: showTopNavMenu ? &#39;none&#39; : &#39;flex&#39;,<br>}</pre><pre>return (<br>   &lt;&gt;<br>     &lt;div id=&quot;nav_container&quot; style={showNav}&gt;<br>       &lt;nav id=&quot;navigation&quot;&gt;{navMenuItems}&lt;/nav&gt;<br>     &lt;/div&gt;<br>     &lt;span className=&quot;menu-icon&quot; style={showMenuIcon}/&gt;<br>   &lt;/&gt;<br>)</pre><p>Here’s what those DOM elements look like in developer tools:</p><p>Desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*QNZIYwoLfH72Ayx_GSkG5A.png" /></figure><p>Tablet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*XMNJC8UK55pg0AUUPc7avg.png" /></figure><p><strong>Pros/Cons</strong></p><p>Pros</p><ul><li>Responsive design no longer depends on an external CSS file</li><li>The Component is more self contained and reusable</li><li>CSS is scoped to this Component with less chance of conflicting CSS</li></ul><p>Cons</p><ul><li>Considerably more work to implement than Media Queries</li><li>Media Queries are more easily and intuitively read</li></ul><h4>Higher Order Components</h4><p>There are quite a few 3rd party libraries to choose from and for this article I went with <a href="https://www.npmjs.com/package/react-socks">React-Socks</a>. Another one that I debated using was <a href="https://www.npmjs.com/package/react-use-media">react-use-media</a>, however, I was looking for a more <a href="https://reactjs.org/docs/higher-order-components.html">Higher Order Component </a>approach which is why I went with React-Socks.</p><p>CodeSandbox: <a href="https://codesandbox.io/s/mars-react-socks-xg8z2">https://codesandbox.io/s/mars-react-socks-xg8z2</a></p><p>Using the library requires installing it via npm or yarn. I’ve used CodeSandbox for these demos and imported it via “Add Dependencies”.</p><p>Once installed we then import the <strong>Breakpoint</strong> and <strong>BreakpointProvider </strong>Components and wrap the top level Component with <strong>BreakpointProvider.</strong></p><pre>import { Breakpoint, BreakpointProvider } from ‘react-socks’;</pre><pre>function App() {</pre><pre>//...rest of App.js above....</pre><pre>return (<br>  &lt;BreakpointProvider&gt;<br>    &lt;Header /&gt;<br>    &lt;Main /&gt;<br>  &lt;/BreakpointProvider&gt;</pre><pre>}</pre><p>This Higher Order Component now provides access to the <strong>Breakpoint</strong> Component in all child Components within the heirarchy.</p><p>The library also provides a few configurations for listening for common breakpoints. The easiest is using <strong>small</strong>, <strong>medium</strong>, and <strong>large</strong> keywords to target breakpoints and then assigning <strong>up</strong> or <strong>down</strong> as to which direction they should apply.</p><p>The nav_container will only show on large desktops and higher (&gt;1023) and the menu-icon will only show on medium and below (&lt;767).</p><pre>&lt;Breakpoint large up&gt;<br>  &lt;div id=”nav_container” &gt;&lt;/div&gt;<br>&lt;/Breakpoint&gt;</pre><pre>&lt;Breakpoint medium down&gt;<br>  &lt;div className=”menu-icon”&gt;&lt;/div&gt;<br>&lt;/Breakpoint&gt;</pre><p>Here’s what those settings look like in developer tools when applied. Take note that the class name syntax uses the <a href="https://www.integralist.co.uk/posts/bem/#4">BEM</a> approach to assigning class names.</p><p><strong>Desktop:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*kWulzuN_NHFRkqAIQ6PqSg.png" /></figure><p><strong>Tablet:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*75nxoCl0UYG-PtxfG6pS6w.png" /></figure><p><strong>Pros/Cons</strong></p><p>Pros</p><ul><li>Easy to implement and configure</li><li>Class names in Dev Tools are semantic and reflect the changes</li></ul><p>Cons</p><ul><li>Noticed a small delay in removing/adding the nav elements</li><li>Didn’t work on inline elements, such as spans, but that might be just a limitation for this library</li><li>Required changing inline elements to block or using divs instead of spans</li></ul><h4>Final Thoughts</h4><p>As React continues to evolve and push the boundaries of Front-End Dev so does our need to rethink old paradigms. If you’re comfortable with Media Queries then by all means keep using them, but as more and more developers lean towards a <a href="https://reactjs.org/docs/faq-styling.html#what-is-css-in-js">CSS-in-JS</a> approach you’ll find yourself hard pressed not to move in that direction.</p><p>Do keep in mind that although the cons of differnt approaches are small in this example, in a real world production application, these cons could exacerbate due to higher complexity and lead to performance issues.</p><p>Special shout out to Thomas Nickels for his additional feedback and comments that helped add some finishing touches to the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcb6ee7eb424" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/3-ways-to-implement-responsive-design-in-your-react-app-bcb6ee7eb424">3 Ways To Implement Responsive Design In Your React App</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Approach To Filtering A D3 Interactive Dashboard]]></title>
            <link>https://itnext.io/one-approach-to-filtering-a-d3-interactive-dashboard-f63e0244f77d?source=rss-87d734551255------2</link>
            <guid isPermaLink="false">https://medium.com/p/f63e0244f77d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[dashboard-design]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Joe Keohan]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 18:19:11 GMT</pubDate>
            <atom:updated>2020-10-19T00:02:35.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGjE_pMxjzxDovsvrbS71g.png" /></figure><p>One key requirement needed in any interactive D3 dashboard, is the implementation of logic to render the data based on the user’s choice of one or more applied filters. Its design should be flexible, and provide the ability to include additional filters based on user requirements.</p><h4>Dashboard Design</h4><p>The idea for this dashboard design was based on the discovery of this <a href="https://interworks.com/blog/dsiegel/2018/02/02/streetball-mecca-mapping-nyc-basketball-courts-tableau/">Tableau Project</a> by <a href="https://interworks.com/people/david-siegel/">David Siege</a>, which I came across while helping a student find a dataset based on basketball courts in NYC. The dataset was limited to just Manhattan and Brooklyn. However, it was a good starting point and being that I’ve worked with Tableau in the past, I knew we would be able to access the existing data by downloading the project. Once I began interacting with the dashboard, I had the thought this would be a great project to recreate using D3.</p><p>The design itself included several sections, each of which allowed the user to interact with the visualization. This entailed attaching D3 <strong>.on()</strong> event listeners to each element which would call the appropriate filter function(s). Although there were several visibly distinct filters, the dashboard also allows the user to interact with individual elements which, by themselves may initiate a re-render of the data. Through some trial and error I believe I implemented a solid approach to keeping track of the possible filter options.</p><h4>Filter Design</h4><p>The first step in working through the filtering logic was to decide which filters would be incorporated in the final design. Below are the clearly defined filters available to the user:</p><ul><li>Legend</li><li>Find A Court</li><li>Select A Borough</li></ul><p>The user is also able to interact via the following:</p><ul><li>Clicking on a specific court on the map or bar chart</li><li>Clicking on a specific court in Must See and Stay Away sections</li><li>Mouseover a specific court or park to initiate a tooltip</li></ul><p>Based on the requirements, I decided to structure the filter options as an array of objects. Each object contains a <strong>key</strong> that was set to the filter name and a <strong>value</strong> that would be initially set to an empty string and then updated based on user interaction.</p><pre>let filters = [<br>  {key:&#39;Overall court grouping&#39;,value:&#39;&#39;},<br>  {key:&#39;Borough&#39;,value:&#39;&#39;},<br>  {key:&#39;Name&#39;,value:&#39;&#39;}</pre><p>The functions responsible for filtering the dataset based on activating the filter would be:</p><ol><li><strong>findActiveFilters():</strong> returns an array of only the active filters</li><li><strong>runFilter(): </strong>returns an array of filtered data based on single filter value</li><li><strong>filterData():</strong> calls <strong>findAcitveFilters</strong> and passes the array of items and single filter to <strong>runFilter. </strong>It then<strong> </strong>returns the final array of filtered elements</li></ol><p>The <strong>findActiveFilters()</strong> function loops over the filters array and returns only those filters that have a value.</p><pre>function findActiveFilters() {<br>  return filters.filter(d =&gt; d.value);<br>}</pre><p>The <strong>runFilter(arr, filter)</strong> function is doing the actual filtering and returning a new array of filtered values. It will be called for each active filter and passed the array that is to be filtered.</p><pre>function runFilter(arr,filter){<br>  return arr.filter( d =&gt; {<br>    return d[filter.key] == filter.value<br>  })<br>}</pre><p>The<strong> filterData() </strong>function<strong> </strong>calls the<strong> findActiveFilters() </strong>function to determine which filters are active and stores those results in <strong>activeFilters</strong>. It then loops over the array and passes <strong>runFilter() </strong>the<strong> allData </strong>array in the first loop and the <strong>filteredData</strong> array in each additional loop. This process continues to reduce the number of elements based on subsequent filters.</p><pre>function filterData() {<br>  let filteredData = [];<br>  let activeFilters = findActiveFilters();<br>  activeFilters.forEach(d =&gt; {<br>    if (filteredData.length == 0) {<br>      filteredData = runFilter(allData, d);<br>    } else {<br>      filteredData = runFilter(filteredData, d);<br>    }<br>  });<br>  return filteredData;<br>}</pre><h4>Initializing The Legend Filter</h4><p>With the filtering system in place it was now up to the individual filters, such as the legend, to first call their supporting filtering functions ,which perform actions specific to that filter. Once complete it then calls the <strong>filterData()</strong> function.</p><p>Initializing the legend filter requires attaching a <strong>.on(‘click’, filterLegend</strong>) event to each rendered legend. The callback here, <strong>filterLegend, </strong>is the filter specific function and is passed the actual element bound to that object, courtesy of D3’s <strong>Data Binding.</strong></p><pre>let legends = gLegends.enter().append(&#39;g&#39;)<br>    .on(&#39;click&#39;, filterLegend)</pre><p>Although you don’t see the element being passed in the above configuration, if we reconfigured it, as seen below, then it would be clear that <strong>filterLegend</strong> is indeed being passed the element directly.</p><pre>let legends = gLegends.enter().append(&#39;g&#39;)<br>    .on(&#39;click&#39;, d =&gt; filterLegend(d)</pre><p>Inside the <strong>filterLegend()</strong> function we first evaluate if there is any need to reset the legend values if the user clicked on the same legend 2x in sequence. The <strong>if </strong>implements that logic, sets <strong>filters[0].value</strong> to an empty string, and reruns the <strong>renderLegend(legend.domain())</strong> function passing it the array of legend values.</p><pre>let legend = d3.scaleOrdinal()<br>  .domain([&quot;Very Good&quot;, &quot;Mediocre&quot;, &quot;Poor&quot;])<br>  .range([&quot;#008000&quot;, &quot;#FF9933&quot;, &quot;#003399&quot;]);</pre><pre>function filterLegend(legendVal){<br>  if(filters[0].value == legendVal) {<br>    filters[0].value = &#39;&#39;<br>    renderLegend(legend.domain())<br>  } else {<br>      filters[0].value = legendVal<br>      renderLegend([legendVal])<br>  } <br>  clearFilterParkValue()<br>  findActiveFilters().length ? <br>     showFilteredData(filterData()) :  showAllData();<br>  filterBarChartBasedOnLegend()</pre><pre>}</pre><p>The <strong>else</strong> is then responsible for setting the <strong>filter[0].value</strong> to the chosen value and then calling <strong>renderLegend([legendVal])</strong> as an array of only one legend value. The renderLegend() function is what rendered the legend initially and was configured to leverage D3’s <strong>update</strong> and <strong>exit </strong>lifecycles to transition the opacity of the legend depending on which one is active.</p><p>Additionally the following functions are also called:</p><ul><li>call <strong>clearFilterParkValue() </strong>to reset all the park specific filters</li><li>ternary operator to call either <strong>showFilteredData()</strong> or <strong>showAllData()</strong></li><li>call <strong>filterBarChartBasedOnLegend()</strong> to reset the bar chart</li></ul><h4>Additional Filter Functions</h4><p>There are several more additional filter type functions that have been created to control filtering. Two additional ones I will mention here are <strong>filterBorough() </strong>and <strong>filterPark(). </strong>Both<strong> </strong>essentially do the same as <strong>filterLegend()</strong>, however, do so within the context of those filters specifically. I’ve included them below as a reference.</p><pre>function filterBorough(boroughVal) {<br>  filters[2].value = &quot;&quot;;<br>  if (boroughVal == &quot;all&quot;) {<br>    filters[1].value = &quot;&quot;;<br>    showAllData()<br>  } else {<br>    filters[1].value = boroughVal;<br>    filteredData = allData.filter(d =&gt; d.Borough == boroughVal)<br>    renderBarChart(nestingData(filteredData));<br>    renderTopParks(filteredData)<br>    renderBottomParks(filteredData)<br>  }<br>  findActiveFilters().length ? <br>     showFilteredData(filterData()) : showAllData();<br>  clearFilterParkValue()<br>}</pre><pre>function filterPark(parkVal) {<br>  if(filters[2].value == parkVal.Name ) {<br>     clearFilterParkValue()<br>  } else {<br>    filterParkValue(parkVal)<br>  }<br>  findActiveFilters().length ? <br>    showFilteredData(filterData()) :  showAllData();<br>}</pre><h3>Conclusion</h3><p>The overall filter functionality took quite a bit of time to work through as there were several nuances to each one. Several supporting functions were configured to support each filter, which may in turn call their own supporting functions. In the end, a major refactor would be needed to make it reusable for a different dataset which in the end I’ll take into consideration when building out the next dashboard.</p><p>Here is the <a href="https://codepen.io/jkeohan/project/full/ZvKkKE">link</a> to the ongoing project. If anyone has any feedback, suggestions or ideas on how to streamline the process even further, I’d love to hear from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f63e0244f77d" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/one-approach-to-filtering-a-d3-interactive-dashboard-f63e0244f77d">One Approach To Filtering A D3 Interactive Dashboard</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>