<?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 Kameron Tanseli on Medium]]></title>
        <description><![CDATA[Stories by Kameron Tanseli on Medium]]></description>
        <link>https://medium.com/@_kamerontanseli?source=rss-815fd058d386------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GPXsqsviVdvgu4ZVr-EHzg.jpeg</url>
            <title>Stories by Kameron Tanseli on Medium</title>
            <link>https://medium.com/@_kamerontanseli?source=rss-815fd058d386------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:58:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_kamerontanseli/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[The rules of reusable components]]></title>
            <link>https://itnext.io/the-rules-of-reusable-components-2b221c138bcf?source=rss-815fd058d386------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b221c138bcf</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kameron Tanseli]]></dc:creator>
            <pubDate>Sat, 10 Nov 2018 21:26:35 GMT</pubDate>
            <atom:updated>2018-11-14T14:09:31.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLg1-G2UAlaKpBopRnmCRg.png" /></figure><p>I spend a lot of my time developing new reusable UI components.</p><p>This means during development I tend to extract UI components that are placed in a shared library or styleguide.</p><p>These components are reused throughout the entire project. Often having different styles or layouts when integrated into features.</p><p>Along the way I learnt a few rules that helped me save time and pain.</p><h4>1. Keep the layout fluid</h4><p>I can’t count the amount of times a component has had a fixed width and that has affected a responsive design. Meaning I have to go in and fiddle with the existing props that was set up in place for another feature somewhere in the site. Not good.</p><p>By keeping the component 100% width you pass the layout responsibility up to the parent component.</p><p>For example it’s a lot easier to use CardOne over CardTwo. As CardOne will respond to the parent&#39;s column changes when the screen size changes.</p><pre>const CardOne = ({ title }) =&gt; (<br>  &lt;div style={{ padding: &quot;20px 30px&quot;, background: &quot;white&quot; }}&gt;{title}&lt;/div&gt;<br>);<br><br>const CardTwo = ({ title }) =&gt; (<br>  &lt;div style={{ width: 600, padding: &quot;10px&quot;, background: &quot;white&quot; }}&gt;<br>    {title}<br>  &lt;/div&gt;<br>);<br><br>const App = () =&gt; (<br>  &lt;div className=&quot;row&quot;&gt;<br>    &lt;div className=&quot;col-md-6&quot;&gt;<br>      &lt;CardOne title=&quot;I&#39;m Fluid&quot; /&gt;<br>    &lt;/div&gt;<br>    &lt;div className=&quot;col-md-6&quot;&gt;<br>      &lt;CardTwo title=&quot;I will break this layout&quot; /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>);</pre><h4>2. Allow extra props to be passed</h4><p>Turns out that your Button component needs a specific data attribute to work with the library you’re using for one of the specific features. Too bad that the Button component only allows className, children and onClick.</p><p>How can we fix this?</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">Modern ES6 JavaScript allows you to spread function parameters and objects</a>. This can be used to feed props to components.</p><pre>// Before -&gt; &lt;button className=&quot;button&quot;&gt;Click me&lt;/button&gt;<br><br>const Button = ({ children, className, onClick }) =&gt; (<br>  &lt;button onClick={onClick} className={`${styles.button} ${className || &quot;&quot;}`}&gt;<br>    {children}<br>  &lt;/button&gt;<br>);<br><br>// After -&gt; &lt;button className=&quot;button&quot; data-theme=&quot;dark&quot;&gt;Click me&lt;/button&gt;<br><br>const Button = ({ className, ...props }) =&gt; (<br>  &lt;button className={`${styles.button} ${className || &quot;&quot;}`} {...props} /&gt;<br>);<br><br>// Example<br><br>const App = ({ onActivate }) =&gt; (<br>  &lt;SpecificFeature&gt;<br>    &lt;Button data-theme=&quot;dark&quot; onClick={onActivate}&gt;<br>      Click me<br>    &lt;/Button&gt;<br>  &lt;/SpecificFeature&gt;<br>);</pre><h3>3. Push logic upwards / Keep it dumb</h3><p>One of the top things that prevents reusability is when stateful logic specific to a feature is implemented within a reusable component.</p><p>Imagine you have a Dropdown component. That you have used in your navigation when a link is clicked.</p><pre>const DropdownItem = ({ className, ...props }) =&gt; (<br>  &lt;li className={`dropdown-item ${className || &quot;&quot;}`} {...props} /&gt;<br>);</pre><pre>class Dropdown extends React.Component {<br>  state = { toggled: false };</pre><pre>  toggle = () =&gt; this.setState(state =&gt; ({ toggled: !state.toggled }));</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;navbar-link&quot;&gt;<br>        &lt;span onClick={this.toggle}&gt; {this.props.title} &lt;/span&gt;<br>        {this.state.toggled &amp;&amp; (<br>          &lt;ul className=&quot;dropdown&quot;&gt; {this.props.children} &lt;/ul&gt;<br>        )}<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>const Navbar = () =&gt; (<br>  &lt;div className=&quot;navbar&quot;&gt;<br>    &lt;div className=&quot;navbar-brand&quot;&gt;Example&lt;/div&gt;<br>    &lt;ul className=&quot;navbar-menu&quot;&gt;<br>      &lt;Dropdown title=&quot;My Account&quot;&gt;<br>        &lt;DropdownItem&gt;One&lt;/DropdownItem&gt;<br>        &lt;DropdownItem&gt;Two&lt;/DropdownItem&gt;<br>      &lt;/Dropdown&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>);</pre><p>The problem above is:</p><ol><li>Dropdown handles the logic for opening and closing the dropdown. Making it a lot harder to reuse Dropdown for more complicated scenarios (e.g: only open the dropdown when a request is successful).</li><li>Dropdown has markup that relates to the Navbar component.</li></ol><p>If we refactor the Dropdown component to push the logic up. We end up with a much more reusable Dropdown component.</p><pre>const DropdownItem = ({ className, ...props }) =&gt; (<br>  &lt;li className={`dropdown-item ${className || &quot;&quot;}`} {...props} /&gt;<br>);</pre><pre>const Dropdown = ({ className, ...props }) =&gt; (<br>  &lt;ul className={`dropdown ${className || &quot;&quot;}`} {...props} /&gt;<br>);</pre><pre>class Navbar extends React.Component {<br>  state = { showUserOptions: false };</pre><pre>  toggleOptions = () =&gt;<br>    this.setState(state =&gt; ({<br>      showUserOptions: !state.showUserOptions<br>    }));</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;navbar&quot;&gt;<br>        &lt;div className=&quot;navbar-brand&quot;&gt;Example&lt;/div&gt;<br>        &lt;ul className=&quot;navbar-menu&quot;&gt;<br>          &lt;div className=&quot;navbar-link&quot;&gt;<br>            &lt;span onClick={this.toggleOptions}&gt;My Account&lt;/span&gt;<br>            {this.state.showUserOptions &amp;&amp; (<br>              &lt;Dropdown&gt;<br>                &lt;DropdownItem&gt;One&lt;/DropdownItem&gt;<br>                &lt;DropdownItem&gt;Two&lt;/DropdownItem&gt;<br>              &lt;/Dropdown&gt;<br>            )}<br>          &lt;/div&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><h3>Summary</h3><ul><li>Keep the component layout fluid.</li><li>Allows extra props to be passed into the component.</li><li>Keep logic out of them as much as possible.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b221c138bcf" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/the-rules-of-reusable-components-2b221c138bcf">The rules of reusable components</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[Testing a component that uses React Hooks]]></title>
            <link>https://medium.com/@_kamerontanseli/testing-a-component-that-uses-react-hooks-e4f9b72ab53c?source=rss-815fd058d386------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4f9b72ab53c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Kameron Tanseli]]></dc:creator>
            <pubDate>Fri, 02 Nov 2018 17:11:20 GMT</pubDate>
            <atom:updated>2018-11-02T17:15:06.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNCvaJoz27hcyN3WzHFwNg.jpeg" /></figure><blockquote>Hooks are a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha and being discussed in an open RFC. — <a href="https://reactjs.org/docs/hooks-intro.html">ReactJS Docs</a></blockquote><p>The component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82e4e4bd69fc63aab7e9ae7dd05fecf7/href">https://medium.com/media/82e4e4bd69fc63aab7e9ae7dd05fecf7/href</a></iframe><p>The test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/461e928574f141d77c44f36f457a7768/href">https://medium.com/media/461e928574f141d77c44f36f457a7768/href</a></iframe><p>The result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fly14jv7yq&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fly14jv7yq&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fly14jv7yq%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1d1ed38f9b1de82ee35e4d5e1a1f939/href">https://medium.com/media/d1d1ed38f9b1de82ee35e4d5e1a1f939/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4f9b72ab53c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilise render props to separate logic from presentation in React]]></title>
            <link>https://itnext.io/utilise-render-props-to-separate-logic-from-presentation-in-react-c5dd0edfa974?source=rss-815fd058d386------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5dd0edfa974</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Kameron Tanseli]]></dc:creator>
            <pubDate>Sun, 10 Jun 2018 21:47:50 GMT</pubDate>
            <atom:updated>2018-06-11T21:14:52.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6C4nSvy2Woe0m7bWEn4BA.png" /><figcaption>React JS</figcaption></figure><p>Separating logic from your presentation has always been a best practise. It enforces the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility principle (SRP)</a> and makes the code easier to test.</p><p>React however gets in trouble for letting developers mush the two concerns together with ease. Lets take an example from the <a href="https://reactjs.org/">homepage</a> to explain:</p><pre>class Timer extends React.Component {<br>  constructor(props) {<br>    super(props)<br>    this.state = { seconds: 0 }<br>  }</pre><pre>  tick() {<br>    this.setState(prevState =&gt; ({ seconds: prevState.seconds + 1 }))<br>  }</pre><pre>  componentDidMount() {<br>    this.interval = setInterval(() =&gt; this.tick(), 1000)<br>  }</pre><pre>  componentWillUnmount() {<br>    clearInterval(this.interval)<br>  }</pre><pre>  render() {<br>    return &lt;<strong>div</strong>&gt;Seconds: {this.state.seconds}&lt;/<strong>div</strong>&gt;<br>  }<br>}</pre><p>Above you can see the rather simple Timer class. You can also see the display logic for the class is coded right into the render() method.</p><p>The problem with having &lt;div&gt;Seconds: {this.state.seconds}&lt;/div&gt; in the Timer class is that it’s not separating logic from presentation.</p><p>Lets separate the two concerns:</p><pre>const SecondsActive = ({ seconds }) =&gt; <br>  &lt;<strong>div</strong>&gt;Seconds: {seconds}&lt;/<strong>div</strong>&gt;;</pre><pre>class TimerContainer extends React.Component {<br>  state = { seconds: 0 }</pre><pre>  tick() {<br>    this.setState(({ seconds }) =&gt; ({ seconds: seconds + 1 }))<br>  }</pre><pre>  componentDidMount() {<br>    this.interval = setInterval(() =&gt; this.tick(), 1000)<br>  }</pre><pre>  componentWillUnmount() {<br>    clearInterval(this.interval)<br>  }</pre><pre>  render() {<br>    return this.props.view({ seconds: this.state.seconds })<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;<strong>TimerContainer</strong> view={SecondsActive} /&gt;,<br>  document.getElementById(&#39;app&#39;)<br>);</pre><p>With a simple switch to rendering via a prop we have made the Timer(TimerContainer) class reusable across many presentational components and have made the presentational component super easy to test!</p><h3>Read more about render props and React</h3><ul><li><a href="https://gist.github.com/chantastic/fc9e3853464dffdb1e3c">JSX, a year in</a></li><li><a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">Presentational and Container Components</a></li><li><a href="https://reactjs.org/">React JS</a></li><li><a href="https://reactpatterns.com/#render-callback">Render Props</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5dd0edfa974" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/utilise-render-props-to-separate-logic-from-presentation-in-react-c5dd0edfa974">Utilise render props to separate logic from presentation in React</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[Flow type checking tips]]></title>
            <link>https://medium.com/@_kamerontanseli/flow-type-checking-tips-393e5323c040?source=rss-815fd058d386------2</link>
            <guid isPermaLink="false">https://medium.com/p/393e5323c040</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <dc:creator><![CDATA[Kameron Tanseli]]></dc:creator>
            <pubDate>Tue, 28 Nov 2017 21:44:09 GMT</pubDate>
            <atom:updated>2017-11-28T21:44:09.471Z</atom:updated>
            <content:encoded><![CDATA[<p>For the past 3 months I have been adding more <a href="https://flow.org/">Flow</a> type checking to a codebase.</p><p>Lots of trial and error went into integrating Flow into the existing legacy code and new code. So I will share what I have learnt with you:</p><h4>Declare types above the component</h4><p>So you have a React.Component and you want to add types to it right? You might be inclined to just add them inline when declaring the component like so:</p><pre>class Greeting extends React.Component&lt;{name: string}, void&gt; {<br> render() {<br>  const {name} = this.props;<br>  return (&lt;div&gt;{name}&lt;/div&gt;); <br> }<br>}</pre><p>What a joy! You have types for your props, everything is wonderful in the world until… you need to add some logic to the constructor:</p><pre>class Greeting extends React.Component&lt;{name: string}, void&gt; {<br> constructor(props: {name: string}) {<br>  super(props);<br>  // some initialisation stuff<br> }<br> render() {<br>  const {name} = this.props;<br>  return (&lt;div&gt;{name}&lt;/div&gt;); <br> }<br>}</pre><p>Now you have added two declarations of the props for this component. The best way to declare types is to extract it into its own type declaration:</p><pre>type GreetingProps = { name: string };</pre><pre>class Greeting extends React.Component&lt;GreetingProps, void&gt; {<br> constructor(props: GreetingProps) {<br>  super(props);<br>  // some initialisation stuff<br> }<br> render() {<br>  const {name} = this.props;<br>  return (&lt;div&gt;{name}&lt;/div&gt;); <br> }<br>}</pre><p>The same logic goes for stateless components which take a large number of props like so:</p><pre>const ToolbarFilter = ({  <br> active,<br> pending,<br> upcoming,<br>  cancelled,<br>  recentlyEdited<br>}:{<br> active: boolean,<br> pending: boolean,<br> upcoming: boolean,<br>  cancelled: boolean,<br>  recentlyEdited: boolean<br>})=&gt; (<br> &lt;div&gt; {/* Some checkboxes here */} &lt;/div&gt;<br>);</pre><p>There is nothing wrong with this approach but it is a lot cleaner to extract it out as well as offering reuse for any parent component above it:</p><pre>// this can be used else where<br>type ToolbarFilters = {<br> active: boolean,<br> pending: boolean,<br> upcoming: boolean,<br>  cancelled: boolean,<br>  recentlyEdited: boolean<br>};</pre><pre>// needed in case of any new props to be added<br>type ToolbarFilterProps = ToolbarFilters;</pre><pre>const ToolbarFilter = ({  <br> active,<br> pending,<br> upcoming,<br>  cancelled,<br>  recentlyEdited<br>}: ToolbarFilterProps)=&gt; (<br> &lt;div&gt; {/* Some checkboxes here */} &lt;/div&gt;<br>);</pre><h4>Extending types</h4><p>Like the above example imagine you have a type called ToolbarFilters and it contains all the available options for filtering some data.</p><p>Now your component ToolbarFilter uses the ToolbarFilters type in its props. How do we use it? Copy and paste? No. We use &amp; to reuse the type:</p><pre>// this can be used else where<br>type ToolbarFilters = {<br> active: boolean,<br> pending: boolean,<br> upcoming: boolean,<br>  cancelled: boolean,<br>  recentlyEdited: boolean<br>};</pre><pre>// see how we added the new onFilterChange<br>type ToolbarFilterProps = ToolbarFilters &amp; {<br> onFilterChange: ($Keys&lt;ToolbarFilters&gt;, boolean)=&gt; void<br>};</pre><pre>const ToolbarFilter = ({  <br> active,<br> pending,<br> upcoming,<br>  cancelled,<br>  recentlyEdited,<br> onFilterChange<br>}: ToolbarFilterProps)=&gt; (<br> &lt;div&gt; {/* Some checkboxes here */} &lt;/div&gt;<br>);</pre><h4>Use React.Element to avoid the issue of not returning a Component</h4><p>We have all been there, where we have written a stateless component and just forgotten to return the JSX:</p><pre>const hello = ({ name }: { name: string })=&gt; {<br> const fullName: string = name.split(&quot;_&quot;).join(&quot; &quot;);<br> (&lt;div&gt;Hello {fullName}&lt;div&gt;);<br>}</pre><p>Then we get the lovely React error to follow it:</p><pre>A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.</pre><p>Not so good. But we can catch this before it ever reaches our browser by using React.Element:</p><pre>import * as React from &#39;react&#39;; <br>// this imports all Flow types into the React namespace</pre><pre>const hello = ({ name }: { name: string }): React.Element&lt;&#39;div&#39;&gt; =&gt; {<br> const fullName: string = name.split(&quot;_&quot;).join(&quot; &quot;);<br> (&lt;div&gt;Hello {fullName}&lt;div&gt;);<br>}</pre><p>Now in this example we get this error:</p><pre>10: }): React.Element&lt;&quot;div&quot;&gt; =&gt; {<br>         ^^^^^^^^^^^^^^^^^^^^ undefined. Inexact type is incompatible with exact type<br> 10: }): React.Element&lt;&quot;div&quot;&gt; =&gt; {<br>         ^^^^^^^^^^^^^^^^^^^^ exact type: object type</pre><pre>Found 1 error</pre><p>There are a lots of other <a href="https://flow.org/en/docs/react/">React Flow types</a> that can be used to add more coverage over a component.</p><h4>Make use of the utility types such as $Keys</h4><p>We’re all in a rush sometimes. So why not learn something that would speed up adding types to our Component. Say we have a component which takes a type prop and returns a component based off that type:</p><pre>const Greeting = ({ type }: { type: string }): React.Element&lt;&#39;h2&#39;&gt; =&gt; {<br> switch (type) {<br>   case &quot;welcome&quot;:<br>  return &lt;h2&gt; Welcome! &lt;/h2&gt;;<br>    default:<br>  return &lt;h2&gt; Hello &lt;/h2&gt;<br>  }<br>};</pre><p>We would only want this type to ideally be restricted to the choices hello or welcome. That is where $Keys comes in. It scans an Object literal and uses it’s keys as a string union.</p><p>So an object like this: {a: 2, b: 3} is turned into ’a’ | ‘b&#39;.</p><p>We can add this type check and refactor:</p><pre>const greetingComponents = {<br>  &#39;welcome&#39;: ()=&gt; &lt;h2&gt; Welcome! &lt;/h2&gt;,<br>  &#39;hello&#39;: ()=&gt; &lt;h2&gt; Hello &lt;/h2&gt;<br>};</pre><pre>type GreetingProps = { <br> type: $Keys&lt;typeof greetingComponents&gt; <br>};</pre><pre>const Greeting = ({ type }: GreetingProps): React.Element&lt;&#39;h2&#39;&gt; =&gt; greetingComponents[type]();</pre><p>If we tried to use the key bye for example it will throw the rather nice error:</p><pre>15: &lt;Greeting type=&#39;bye&#39; /&gt;<br>                     ^ property `bye`. Property not found in<br>7:  type: $Keys&lt;typeof greetingComponents&gt; <br>          ^ object literal</pre><p>Flow offers a bunch of really useful utility types that you can read about <a href="https://flow.org/en/docs/types/utilities/#toc-keys">here</a>.</p><h4>Move all reused types to a separate file</h4><p>You may notice as you build out your React app that a certain type is used in multiple places. You may decide to just import the type from that one component: import type {State} from ‘../some/component’ .</p><p>But this will slowly get out of hand.</p><p>My suggestion is to create a types.js file in the root of your app to keep reference .</p><p>This file should contain:</p><ul><li>Only app wide shared types (if its feature wide then create another types.js inside that feature folder).<br>2. Redux types like the InitialState for reducers etc.<br>3. Only flow types.</li></ul><h4>If you want an object to be immutable then you can type check it</h4><p>You really don’t want some component messing around with your state. So why not protect against it by declaring that object as immutable:</p><pre>type AppConfig = {<br> +apiKey: string // the &#39;+&#39; makes it immutable in Flow<br>};</pre><pre>const Settings: AppConfig = {<br> apiKey: &#39;rihfwefiweufweiufgewfugew84r34t3&#39;<br>};</pre><pre>// later on....</pre><pre>Settings.apiKey = &#39;fiohwefoihefoihfoeihfewifhwfihefhwoef&#39;;</pre><p>Flow helps protect against the change by throwing this error:</p><pre>11: Settings.apiKey = &#39;fiohwefoihefoihfoeihfewifhwfihefhwoef&#39;;<br>    ^ object type. Covariant property `apiKey` incompatible with contravariant use in</pre><pre>11: Settings.apiKey = &#39;fiohwefoihefoihfoeihfewifhwfihefhwoef&#39;;<br>    ^ assignment of property `apiKey`</pre><h4>Read the documentation &amp; find references</h4><p>I can’t stress this enough how detailed the Flow docs are at explaining things. The most useful links I have found are as follows:</p><p>1. <a href="https://flow.org/en/docs/react/components/">Components | Flow</a><br>2. <a href="https://flow.org/en/docs/react/redux/">Redux | Flow</a><br>3. <a href="https://flow.org/en/docs/react/children/">Children | Flow</a><br>4. <a href="https://flow.org/en/docs/lang/refinements/">Type Refinements | Flow</a><br>5. <a href="https://www.saltycrane.com/flow-type-cheat-sheet/latest/#lib/dom.js">Flow DOM cheat sheet</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=393e5323c040" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 ways to level up your JavaScript code]]></title>
            <link>https://medium.com/@_kamerontanseli/9-ways-to-level-up-your-javascript-code-9da0cbcd43c5?source=rss-815fd058d386------2</link>
            <guid isPermaLink="false">https://medium.com/p/9da0cbcd43c5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kameron Tanseli]]></dc:creator>
            <pubDate>Sat, 08 Apr 2017 09:20:39 GMT</pubDate>
            <atom:updated>2017-05-28T06:54:24.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>1. Don’t use commas when declaring variables</h4><pre>var a = 2,<br>    b = a + 2,<br>    c = b - 3;</pre><pre>var a = 2;<br>var b = a + 2;<br>var c = b - 3;</pre><ul><li>variables can be easily moved around from line to line without having to worry about the commas.</li></ul><h4>2. Namespace all your code</h4><pre>var fruit = &quot;apple&quot;;</pre><pre>var fruit = [&quot;apple&quot;, &quot;pear&quot;]; // namespace collision</pre><pre>window.Basket = window.Basket || {};<br>Basket.fruit = &quot;apple&quot;;</pre><pre>window.Stock = window.Stock || {};<br>Stock.fruit = &quot;apple&quot;;</pre><ul><li>Stops naming collisions</li></ul><h4>3. Utilize the Module pattern</h4><pre>var Basket = (()=&gt;{<br>  var items = [];<br>  return {<br>     addItem: ()=&gt; {},<br>     removeItem: (index)=&gt; {}<br>  };<br>})();</pre><ul><li>The closure created by the Immediately Invoked Function Expression (IIFE) allows privacy. E.g: The items array is only accessible through the returned methods.</li><li><a href="https://toddmotto.com/mastering-the-module-pattern/">Link to more indepth article</a></li></ul><h4>4. Comment your code</h4><pre>/** Class representing a point. */<br>class Point {<br>    /**<br>     * Create a point.<br>     * @param {number} x - The x value.<br>     * @param {number} y - The y value.<br>     */<br>    constructor(x, y) {<br>        // ...<br>    }<br>}</pre><ul><li>Allows developers to get a deeper understanding of what is happening in your code</li><li>Can be used to generate online documentation guides</li><li>Industry standard is <a href="http://usejsdoc.org/about-getting-started.html">JSDOC</a></li></ul><h4>5. Learn design patterns</h4><ul><li><a href="http://www.dofactory.com/javascript/observer-design-pattern">The Observer pattern</a> helps your modules communicate to each other through events thus providing loose coupling in your app.</li><li><a href="http://www.dofactory.com/javascript/mediator-design-pattern">The Mediator pattern</a> takes control over a group of objects by encapsulating how these objects interact. E.g: a basket that handles items.</li><li><a href="http://www.dofactory.com/javascript/iterator-design-pattern">The Iterator pattern</a> is the underlying pattern for ES2015 generators. Useful to know whats actually going on :D</li><li><a href="http://www.dofactory.com/javascript/facade-design-pattern">The Facade pattern</a> provides an simple interface which encapsulates the end user from complex functionality. E.g: Email module with simple methods such as start, stop and pause;</li></ul><p>Not only are these solutions to commonly solved problems, they are a way of describing application structure to other developers fairly simply. E.g: “The basket module is a mediator for all the store items, it communicates to the payment module via an observer”.</p><h4>6. Pass objects into functions with a large number of arguments</h4><pre>function colorWidget(element, colorValue, colorRange, colorFormat, opacity, onChange) {<br>  <br>}</pre><pre>colorWidget($(&quot;&lt;div/&gt;&quot;), &quot;#fff&quot;, ...);</pre><pre>function colorWidget(options) {<br>    var config = _.extend({<br>      element: $(&quot;&lt;div/&gt;&quot;),<br>      colorValue: &quot;#000&quot;,<br>      colorRange: [0, 255],<br>      colorFormat: &quot;rgb&quot;,<br>      opacity: 0.8,<br>      onChange: function(){}<br>    }, options); <br>}</pre><pre>colorWidget({<br>   element: $(&quot;&lt;div/&gt;&quot;)<br>});</pre><ul><li>Allows new arguments to be added easily</li><li>The developer doesn’t have to worry about the order of the arguments</li><li>Allows the setting of default values easily</li></ul><p>This is most commonly seen in the creation of <a href="https://learn.jquery.com/plugins/basic-plugin-creation/#accepting-options">jQuery plugins.</a></p><h4>7. Don’t use type constructors unless specifically necessary</h4><pre>var x1 = new Object();<br>var x2 = new String();<br>var x3 = new Number();<br>var x4 = new Boolean();<br>var x5 = new Array();<br>var x6 = new RegExp(&quot;()&quot;);<br>var x7 = new Function();</pre><pre>var x1 = {};           <br>var x2 = &quot;&quot;;           <br>var x3 = 0;            <br>var x4 = false;        <br>var x5 = [];           <br>var x6 = /()/;         <br>var x7 = function(){};</pre><ul><li>Creation through type constructors is significantly slower.</li><li>Because the end result of the constructor is an Object rather than a primitive value you get nasty side effects like so:</li></ul><pre>var a = new String(&quot;x&quot;);<br>a === &quot;x&quot;  //false<br>a == &quot;x&quot; //true</pre><pre>var b = &quot;dog&quot;;<br>b.woof = true;<br>b.woof; // undefined</pre><pre>var c = new String(&quot;dog&quot;);<br>c.woof = true;<br>c.woof; // true</pre><ul><li><a href="http://stackoverflow.com/questions/5750656/whats-the-point-of-new-stringx-in-javascript">You can see more about this here</a></li></ul><h4>8. Make sure your context is right</h4><pre>var Button = {<br>  count: 0,<br>  click: function() {<br>    this.count += 1;<br>  },<br>  init: function() {<br>    $(&quot;button&quot;).click(this.click);<br>  }<br>};</pre><pre>Button.init();</pre><p>From a glance this should work however when a user clicks the button we will get an error that count doesn’t exist. This is because the click function is executed in the context of the $(&quot;button&quot;) element instead of the Button object. We can fix this by binding the context to the function:</p><pre>$(&quot;button&quot;).click(this.click.bind(this));<br>// or<br>$(&quot;button&quot;).click(()=&gt; this.click());</pre><h4>9. Apply</h4><blockquote>The <strong>apply()</strong> method calls a function with a given this value and arguments provided as an array (or an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array-like object</a>). — MDN</blockquote><p>Some useful instances of using apply:</p><pre>// emulating &quot;super&quot; in an constructor <br>SomeConstructor.prototype.somemethod.apply(this, arguments);</pre><pre>// passing an array of promises to jQuery.when<br>$.when.apply($, [$.get(), $.get()]);</pre><pre>// finding the max number in an array<br>Math.max.apply(Math.max, [1,2,3,4,5]);</pre><h4>Bonus Points</h4><p>Contributed by: <a href="https://medium.com/u/e2ccfc311d48">Russley Shaw</a></p><h4>10. Use let and const over var</h4><p><strong>let</strong> allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.</p><p>Lets look at a few use cases where this is useful over var statements:</p><pre>var elements = document.querySelectorAll(&#39;p&#39;);<br>for (var i = 0; i &lt; elements.length; i++) {                                 <br>    // have to wrap in IIFE other i would be elements.length<br>    (function(count){  <br>       elements[count].addEventListener(&#39;click&#39;, function(){<br>           elements[count + 1].remove();<br>       });<br>     })(i);<br>}</pre><pre>// using let<br>let elements = document.querySelectorAll(&#39;p&#39;);<br>for (let i = 0; i &lt; elements.length; i++) {<br>   elements[i].addEventListener(&#39;click&#39;, function(){<br>        elements[i + 1].remove();<br>   });<br>}</pre><p>The reason why the top example would be elements.length is because i is referenced directly so on the next iteration i is incremented. When we wrap the code in an IIFE we reference i under the parameter count thus removing the direct reference.</p><p>const allows the declaration of variables that cannot be re referenced. This is useful for declaring constants (the keyword originates from it).</p><pre>const API_KEY = &#39;2rh8ruberigub38rt4tu4t4&#39;;<br>const PI = 3.14;</pre><p>However objects and arrays can still be accessed and changed. To stop this use Object.freeze() :</p><pre>const API_CONFIG = Object.freeze({<br>  &#39;key&#39;: &#39;8ry4iuggi4g38430t5485jmub&#39;,<br>  &#39;endpoint&#39;: &#39;/some/boring/api/path/&#39;<br>});</pre><pre>API_CONFIG.key = null; // attempt to change<br>API_CONFIG.key; //= &#39;8ry4iuggi4g38430t5485jmub&#39;</pre><pre>const EVENS = Object.freeze([ 2, 4, 6, 8]);<br>EVENS[2] = 9;<br>EVENS[2]; //= 6</pre><h4>11. Avoid using “or” when referencing variables</h4><p>The only reason to avoid doing this is when the variable is <strong>allowed</strong> to be false . Take a look at the example below:</p><pre>var msg = &#39;&#39;; //= should hide the button<br>var btnMsg = msg || &#39;Click Me&#39;;</pre><pre>btnMsg; //= &#39;Click Me&#39;</pre><p>The reason this happens is due to the conversion of the &quot;” into a Boolean which returns false . As the &quot;” is counted as false the or comparison returns the other side Click Me .</p><p>If you want to have shorthand if statements you can use the <strong>ternary operator:</strong></p><pre>var msg = &#39;&#39;; //= should hide the button<br>var btnMsg = msg.length &lt; 1 ? msg : &#39;Click Me&#39;;</pre><pre>btnMsg; //= &#39;&#39;</pre><h3>If you found this helpful, follow me on <a href="https://www.instagram.com/kameron_tanseli/">Instagram</a> :D</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9da0cbcd43c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Guide to using interfaces with JavaScript]]></title>
            <link>https://medium.com/@_kamerontanseli/quick-guide-to-using-interfaces-with-javascript-5a557f635e11?source=rss-815fd058d386------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a557f635e11</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kameron Tanseli]]></dc:creator>
            <pubDate>Mon, 19 Dec 2016 21:56:59 GMT</pubDate>
            <atom:updated>2016-12-19T21:56:59.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Interfaces are great for when you need to enforce some rules about how a developer builds a class. For example we have a Form class, this class is composed of lots of Fields/Inputs. Instead of writing logic to handle all different types of inputs we can define a common <strong>interface</strong> between them all.</p><p>Our Interface will contain a render() method to render out the input and a value() method to get the input’s value.</p><pre>var required = function(){ throw new Error(&quot;Implement!&quot;); };<br>var InputInterface = {<br>    render: required,<br>    value: required<br>};</pre><p>We can apply the Interface to a Base Input class so that all of our derived classes have the Interface.</p><pre>function Input(){}<br>Input.prototype = Object.create(InputInterface);</pre><p>Now whenever you call render() you will get an Implementation Error. This forces the developer to override the Base class’s methods. Thus you have forced them to implement the interface.</p><pre>function Checkbox(){ <br>    this.$el = $(&quot;&lt;input/&gt;&quot;, { type: &quot;checkbox&quot; }); <br>}<br>Checkbox.prototype = Object.create(Input); // inherit<br>Checkbox.prototype.render = function(){ return this.$el; };<br>Checkbox.prototype.value = function(){ <br>    return this.$el.prop(&quot;checked&quot;); // override methods<br>};</pre><h3>If you have any questions regarding this article, you can find me on Instagram: <a href="https://www.instagram.com/kameron_tanseli/">kameron_tanseli</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a557f635e11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing reusable JavaScript]]></title>
            <link>https://medium.com/@_kamerontanseli/writing-reusable-javascript-d220aa501e67?source=rss-815fd058d386------2</link>
            <guid isPermaLink="false">https://medium.com/p/d220aa501e67</guid>
            <category><![CDATA[reusable]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[small]]></category>
            <category><![CDATA[vanillajs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kameron Tanseli]]></dc:creator>
            <pubDate>Wed, 14 Dec 2016 23:44:28 GMT</pubDate>
            <atom:updated>2016-12-14T23:44:28.757Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Don’t reinvent the wheel, just realign it. — Anthony J. D’Angelo</blockquote><h4>It is the small things that count</h4><p>Small problems are usually overlooked by the developer, I myself have rushed and wrote sloppy functions as I had lack of care for the smaller problem.</p><p>An example of rushing:</p><pre>$(&quot;button&quot;).click(function(){<br>   var heading = $(&quot;h1&quot;).text();<br>   var capital = heading[0].toUpperCase() + heading.slice(1);<br>   $(&quot;h1&quot;).text(capital);<br>});</pre><p>How can we improve this? Right away we can pull out the entire function so it is no longer an anonymous function, <a href="https://developers.google.com/web/tools/chrome-devtools/javascript/step-code">this helps when we need to debug</a> and allows us to reuse this block of code:</p><pre>function capitalizeHeading() {<br>   var heading = $(&quot;h1&quot;).text();<br>   var capital = heading[0].toUpperCase() + heading.slice(1);<br>   $(&quot;h1&quot;).text(capital);<br>}</pre><pre>$(&quot;button&quot;).click(capitalizeHeading);</pre><p>Lets make this even more useful and extract the capitalizing logic:</p><pre>function capitalize(word) {<br>   return word[0].toUpperCase() + word.slice(1);<br>}</pre><pre>function capitalizeHeading() {<br>   var heading = $(&quot;h1&quot;).text();<br>   $(&quot;h1&quot;).text(capitalize(heading));<br>}</pre><pre>$(&quot;button&quot;).click(capitalizeHeading);</pre><p>Now we can reuse the capitalizing logic across our program.</p><p>Did you know that<a href="https://github.com/jquery/jquery/blob/master/src/core.js#L34"> jQuery constructs a new Object and queries the DOM every time you call <em>$(&lt;selector&gt;)</em></a><em>?. </em>We should cache jQuery objects in order to speed up execution times:</p><pre>function capitalize(word) {<br>   return word[0].toUpperCase() + word.slice(1);<br>}</pre><pre>function capitalizeHeading() {<br>   var $h1 = $(&quot;h1&quot;); // cache h1 in a variable<br>   $h1.text(capitalize($h1.text())); // reuse without creating<br>}</pre><pre>$(&quot;button&quot;).click(capitalizeHeading);</pre><p><em>capitalizeHeading </em>is okay for this one use case but it would be much more useful if it accepted a parameter to indicate what elements to capitalize:</p><pre>function capitalize(word) {<br>   return word[0].toUpperCase() + word.slice(1);<br>}</pre><pre>function capitalizeElement(element) {<br>   var $el = $(element);<br>   $el.text(capitalize($el.text()));<br>}</pre><pre>$(&quot;button&quot;).click(capitalizeElement.bind(capitalizeElement, &quot;h1&quot;));</pre><p>We can use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind"><em>bind</em></a><em> </em>in order to create a partial function. This is a function which has its arguments preloaded before execution, in this case we have made the <em>element </em>parameter a “h1”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*nokd0ixUsnu8xziT6KpUoA.png" /><figcaption>Bind in action</figcaption></figure><p>Turning <em>capitalizeHeading </em>into <em>capitalizeElement(&lt;element&gt;)</em> allows us to reuse that function for any element we wish to capitalize:</p><pre>capitalizeElement(&quot;h2&quot;);<br>capitalizeElement(&quot;div[data-title]&quot;);</pre><p>We have split the original callback into 2 reusable functions. By doing so we have begun to follow the <a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself">DRY (Don’t Repeat Yourself)</a> principle.</p><h3>If you have any questions regarding this article, you can find me on Instagram: <a href="https://www.instagram.com/kameron_tanseli/">kameron_tanseli</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d220aa501e67" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>