<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: David Clark</title>
    <description>The latest articles on DEV Community by David Clark (@daviddoes).</description>
    <link>https://dev.to/daviddoes</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F77255%2F4fe2af1f-4ee8-4d7f-9e54-6aac37cc3a0b.jpg</url>
      <title>DEV Community: David Clark</title>
      <link>https://dev.to/daviddoes</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/daviddoes"/>
    <language>en</language>
    <item>
      <title>Creating a Dynamic &lt;select&gt; Menu with React</title>
      <dc:creator>David Clark</dc:creator>
      <pubDate>Thu, 25 Jul 2019 01:14:46 +0000</pubDate>
      <link>https://dev.to/daviddoes/creating-a-dynamic-select-menu-with-react-52fm</link>
      <guid>https://dev.to/daviddoes/creating-a-dynamic-select-menu-with-react-52fm</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;a href="https://medium.com/l2code/creating-a-dynamic-select-menu-with-react-701950fbedd6"&gt;originally posted to medium&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;I must say — this was a somewhat difficult feature for me to figure out how to implement. I looked at libraries such as &lt;a href="https://react-select.com/home"&gt;react-select&lt;/a&gt; and other’s implementations of similar features, but just couldn’t find what I was looking for. Stepping out of everyone’s comfort zone of using someone else’s hard work, I greased up my elbows and set to work.&lt;/p&gt;

&lt;p&gt;React is still new to me, along with everything that is software development. Therefore, it takes a bit more mental computation to understand exactly what I’m trying to accomplish.&lt;/p&gt;

&lt;p&gt;In this case, I needed to understand how to get previously-stored values into a  element in a form. The idea is that the user is utilizing this form to record meditation sessions — or what I refer to as &lt;em&gt;mindful moments&lt;/em&gt; — and in this form the user records the location where they had that mindful moment. Chances are they’re going to meditate in the same location more than once, so we need to make it so that the user can either use an already-existing location, or create a new one.&lt;/p&gt;

&lt;h3&gt;
  
  
  Code Walk-through
&lt;/h3&gt;

&lt;p&gt;Let’s see how to do this…&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// LocationSelect component

import React from 'react';
import { connect } from 'react-redux';
import { getMoments } from '../actions/moments';
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Of course, we need to import React and connect, and also the action to get our list of moments — a call to our API — which contains the location that we need for our  later on.&lt;/p&gt;

&lt;p&gt;Let’s initialize our component’s state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LocationSelect extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      location: ''
    };
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So we’re telling our component to store a location key in its state, but not yet giving it a value. We just giving that value a place to go later on.&lt;/p&gt;

&lt;p&gt;Let’s get our moments object from our API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  componentDidMount(){
    if (this.props.authToken){
     getMoments(this.props.authToken);
    }
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;If&lt;/em&gt; our props contains the authToken , then run the getMoments action with that authToken. We want this to happen once this component mounts.&lt;/p&gt;

&lt;p&gt;Inside our render(), we want to sort our select menu’s options to make it more user-friendly. To do this, we need to first get all of our previously-entered data, store it in a new array, then sort that array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;render() {
  let momentsList = [];
  this.props.moments.forEach(({ id, location }) =&amp;gt; momentsList.push({ id, location }));

  let uniqueSet = [...new Set(momentsList.map(moment =&amp;gt; moment.location))];
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So we create our new array, momentsList. Since they’re passed as props, we need to grab them from there, and run a forEach, grabbing the id and the location from &lt;em&gt;each&lt;/em&gt; iteration (in this case, each moment). Then, we’re pushing id and location into our new array from each moment we iterate over. We only want the id and location, not any other information that might be stored in that object.&lt;/p&gt;

&lt;p&gt;We then need to create a new Set, so that we can store data of any type. We’re saying, &lt;em&gt;Create a new array called uniqueSet, which will be a new Set created from a map() over our previous array, grabbing the location&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;*I know this is rather messy — I’d love to know of a more succinct way to do this if possible!&lt;/p&gt;

&lt;p&gt;Next, let’s sort that new array alphabetically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let sortedList = uniqueSet.sort()
  .map((location, index) =&amp;gt; &amp;lt;option key={index}&amp;gt;{location}&amp;lt;/option&amp;gt;);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The default behavior of &lt;code&gt;sort()&lt;/code&gt; is to sort alphabetically.&lt;/p&gt;

&lt;p&gt;Our map function is taking the location and index of each of those now-sorted items and putting them into an array for our  to use later. Notice we’re using the index as our key for React, and location as our text to display.&lt;/p&gt;

&lt;p&gt;Inside our return statement is where we’re going to see all of this come to fruition on the user-side.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
      &amp;lt;div className="dropdown"&amp;gt;
        &amp;lt;label htmlFor="location"&amp;gt;Location&amp;lt;/label&amp;gt;
        &amp;lt;input
          required
          className="form-input"
          type="text"
          name="location"
          placeholder="create or choose"
          value={this.props.location}
          onChange={event =&amp;gt; this.handleTextFieldChange(event, 'location')}
          maxLength="20"
          autoComplete="off"
        /&amp;gt;
        &amp;lt;select onChange={event =&amp;gt; this.handleTextFieldChange(event, 'location')}&amp;gt;
          {sortedList}
        &amp;lt;/select&amp;gt;
      &amp;lt;/div&amp;gt;
    );
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here you can see that we are rendering to the page an  and our . Our input is the text field used to create a new location, while our select is where we’re rendering all previously-enter location items.&lt;/p&gt;

&lt;p&gt;Our select is receiving our sortedList array to be used as s — remember when we wrote that above?&lt;/p&gt;

&lt;p&gt;If we scroll up in our imaginative document here, we need to write our onChange handler, handleTextFieldChange.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handleTextFieldChange(event) {
    let location = event.target.value;
    let text = location // capitalize first letter
      .toLowerCase()
      .split(' ')
      .map(s =&amp;gt; s.charAt(0).toUpperCase() + s.substr(1))
      .join(' ');
    this.props.setLocation(text, 'location');
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;event.target.value is either our input or our select. If we type into our input field, or if we select an option from the menu. We’re also manipulating all text that gets put into that input field; we’re capitalizing the first character. This helps to keep things looking tidy. Users might feel like capitalizing one day, or using all lowercase the next. This way, our stored data is uniform. You can read more about this in &lt;a href="https://dev.to/daviddoes/react-how-to-manipulate-input-values-before-storing-to-state-4n8d"&gt;my previous post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Then we finish off our component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mapStateToProps = state =&amp;gt; ({
  moments: state.moments.moments,
  authToken: state.auth.authToken
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default connect(mapStateToProps)(LocationSelect);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and render it in our parent component after importing it.&lt;/p&gt;

&lt;p&gt;I understand this is a rough how-to. As one with not a ton of experience with React and JavaScript, and having no one in-person to bounce ideas off of, I was left with reading docs and seeing what others have done. I never did find something doing this same thing, so I had to utilize what I could piece together. For instance, Set is very new to me, and I honestly don’t think I used it in the correct manner. That said, it’s what worked for what I needed.&lt;/p&gt;

&lt;p&gt;I do hope this has helped someone, and I very much welcome any and all input. Below, you can find the component in its entirety:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { connect } from 'react-redux';
import { getMoments } from '../actions/moments';

class LocationSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      location: ''
    };
  }

componentDidMount() {
    if (this.props.authToken) {
      getMoments(this.props.authToken);
    }
  }

handleTextFieldChange(event) {
    let location = event.target.value;
    let text = location // capitalize first letter
      .toLowerCase()
      .split(' ')
      .map(s =&amp;gt; s.charAt(0).toUpperCase() + s.substr(1))
      .join(' ');
    this.props.setLocation(text, 'location');
  }

render() {
    let momentsList = [];
    this.props.moments.forEach(({ id, location }) =&amp;gt; momentsList.push({ id, location }));
    let uniqueSet = [...new Set(momentsList.map(moment =&amp;gt; moment.location))];

// sort list alpha, map to render
    let sortedList = uniqueSet
      .sort((a, b) =&amp;gt; {
        if (a &amp;lt; b) return -1;
        else if (a &amp;gt; b) return 1;
        return 0;
      })
      .map((location, index) =&amp;gt; &amp;lt;option key={index}&amp;gt;{location}&amp;lt;/option&amp;gt;);

// store locations to state
    return (
      &amp;lt;div className="dropdown"&amp;gt;
        &amp;lt;label htmlFor="location"&amp;gt;Location&amp;lt;/label&amp;gt;
        &amp;lt;input
          required
          className="form-input"
          type="text"
          name="location"
          placeholder="create or choose"
          value={this.props.location}
          onChange={event =&amp;gt; this.handleTextFieldChange(event, 'location')}
          maxLength="20"
          autoComplete="off"
        /&amp;gt;
        &amp;lt;select onChange={event =&amp;gt; this.handleTextFieldChange(event, 'location')}&amp;gt;
          {sortedList}
        &amp;lt;/select&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}


const mapStateToProps = state =&amp;gt; ({
  moments: state.moments.moments,
  authToken: state.auth.authToken
});

export default connect(mapStateToProps)(LocationSelect);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Changelog&lt;/strong&gt;&lt;br&gt;
July 25, 2019&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;fix formatting errors carried over from Medium&lt;/li&gt;
&lt;li&gt;update &lt;code&gt;.sort()&lt;/code&gt; code block&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>guide</category>
    </item>
    <item>
      <title>How does this alphabetical-sorting function work?</title>
      <dc:creator>David Clark</dc:creator>
      <pubDate>Thu, 25 Jul 2019 01:14:29 +0000</pubDate>
      <link>https://dev.to/daviddoes/how-does-this-alphabetical-sorting-function-work-5bg4</link>
      <guid>https://dev.to/daviddoes/how-does-this-alphabetical-sorting-function-work-5bg4</guid>
      <description>&lt;p&gt;I'm pretty sure I wrote this function based off of someone else's that I saw. Trouble is, I'm looking back through some code, and I don't fully understand how it works. &lt;/p&gt;

&lt;p&gt;What I have is a &lt;code&gt;Set&lt;/code&gt; that I'm sorting alphabetically. That Set is named, aptly, &lt;code&gt;uniqueSet&lt;/code&gt;. Here's the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let sortedList = uniqueSet
  .sort((a, b) =&amp;gt; {
    if (a &amp;lt; b) return -1;
    else if (a &amp;gt; b) return 1;
    return 0;
  })
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



</description>
      <category>beginners</category>
      <category>help</category>
      <category>explainlikeimfive</category>
    </item>
    <item>
      <title>[React] How to manipulate input values before storing to state. </title>
      <dc:creator>David Clark</dc:creator>
      <pubDate>Thu, 20 Jun 2019 00:01:11 +0000</pubDate>
      <link>https://dev.to/daviddoes/react-how-to-manipulate-input-values-before-storing-to-state-4n8d</link>
      <guid>https://dev.to/daviddoes/react-how-to-manipulate-input-values-before-storing-to-state-4n8d</guid>
      <description>&lt;p&gt;While working on a project, I decided it was important to do some manipulating of input values before storing it to state. Namely, capitalizing the first letter of each word the user types into that field. &lt;/p&gt;

&lt;p&gt;I wasn't sure how to do this in JavaScript, and I wasn't 100% sure how to implement that capitalization behavior into my React component before it was stored to state (this might seem obvious to most, but I've spent a few weeks away from this project). &lt;/p&gt;

&lt;p&gt;After all was said and done, I realized there wasn't a lot out there on this that I'd seen, so I'm sharing it here with you all. &lt;/p&gt;

&lt;h2&gt;
  
  
  Where Do We Do It?
&lt;/h2&gt;

&lt;p&gt;If we look at our components, we probably have one for each form, or even each field. Inside there, we have what are called &lt;code&gt;handlers&lt;/code&gt;. These little buddies take our inputs and do something with them. Chances are, storing it to our state. &lt;/p&gt;

&lt;p&gt;This handler might look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  handleInput(event, key) {
    this.setState({
      [key]: event.target.value
    });
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;What this does, is stores the &lt;code&gt;value&lt;/code&gt; of the input field (so, whatever the user types or selects) and plunks it into this component's state object, at the &lt;code&gt;key&lt;/code&gt; that is passed from our &lt;code&gt;onChange&lt;/code&gt; event. &lt;/p&gt;

&lt;p&gt;Our input with &lt;code&gt;onChange&lt;/code&gt; might look like this (usually more going on here, but let's keep it simple for this):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    &amp;lt;input
      required
      type="text"
      onChange={event =&amp;gt; this.handleInput(event, 'firstName')}
    /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Our &lt;code&gt;onChange&lt;/code&gt; is saying to run the &lt;code&gt;handleInput&lt;/code&gt; handler, passing the &lt;code&gt;event&lt;/code&gt; values and the &lt;code&gt;firstName&lt;/code&gt; key. &lt;/p&gt;

&lt;p&gt;Our state, then, might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.state = {
  firstName: '',
  lastName: '',
  age: ''
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;If what we pass in our &lt;code&gt;onChange&lt;/code&gt; doesn't match a key in our state object, this will not work. &lt;/p&gt;

&lt;p&gt;All that said – still, where do we do it? &lt;/p&gt;

&lt;p&gt;Our &lt;code&gt;handler&lt;/code&gt; is the perfect place to do this. We're going to pass the data on from our input's &lt;code&gt;onChange&lt;/code&gt;, up to our &lt;code&gt;handleInput&lt;/code&gt;. Before we &lt;code&gt;setState&lt;/code&gt;, we'll perform our logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do we do it?
&lt;/h2&gt;

&lt;p&gt;I wasn't entirely sure how to do this myself, so I had to do some hunting. I knew we'd have to &lt;code&gt;split&lt;/code&gt; and &lt;code&gt;join&lt;/code&gt; and &lt;code&gt;toUpperCase&lt;/code&gt; some things, but wasn't entirely sure beyond that. &lt;/p&gt;

&lt;p&gt;Turns out, it's quite easy. &lt;/p&gt;

&lt;p&gt;First of all, let's understand &lt;em&gt;what&lt;/em&gt; we are doing it to. Simply put, we need to manipulate our &lt;code&gt;event.target.value&lt;/code&gt;, which is whatever the user inputs into that field.&lt;/p&gt;

&lt;p&gt;Here are all the things we need to perform on our &lt;code&gt;event.target.value&lt;/code&gt; input to capitalize the first letter of each word:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      .toLowerCase()
      .split(' ')
      .map(s =&amp;gt; s.charAt(0).toUpperCase() + s.substr(1))
      .join(' ');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;toLowerCase()&lt;/code&gt; is first making every character lower case. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;split(' ')&lt;/code&gt; takes each character in our original string (&lt;code&gt;event.target.value&lt;/code&gt;) and splits them into an array equal to each character in that string. So if our user provided John, we would get &lt;code&gt;[j,o,h,n]&lt;/code&gt;. This allows us to &lt;code&gt;map&lt;/code&gt; over each character.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;map(s ...)&lt;/code&gt; - Here, we're using &lt;code&gt;s&lt;/code&gt; to represent each iteration, so each character, which is a single-character string.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;map(s =&amp;gt; s.charAt(0) ...)&lt;/code&gt; - if our iteration is the character at the &lt;code&gt;0&lt;/code&gt; place in our array...&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;map(s =&amp;gt; s.charAt(0).toUpperCase()&lt;/code&gt; then capitalize it...&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;map(s =&amp;gt; s.charAt(0).topupperCase() + s.substr(1))&lt;/code&gt; - this one is tougher to explain. &lt;code&gt;substr&lt;/code&gt; (short for &lt;code&gt;substring&lt;/code&gt;) returns the part of the string at the index value you define, and anything after it. In this case, everything but the first index value. Alternatively, we could use it to return maybe just the first two indexes &lt;code&gt;(0, 1)&lt;/code&gt; or &lt;code&gt;Jo&lt;/code&gt;. We use the &lt;code&gt;+&lt;/code&gt; to combine (concatenate) all of the array items together.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So here's what our code should look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    let capsText = event.target.value
      .toLowerCase()
      .split(' ')
      .map(s =&amp;gt; s.charAt(0).toUpperCase() + s.substr(1))
      .join(' ');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, if we &lt;code&gt;console.log(capsText)&lt;/code&gt;, you'll see we get exactly what we want. How do we store that in state? &lt;/p&gt;

&lt;p&gt;Simple!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    this.setState({
      [key]: capsText
    });
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Let's put it all together!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  handleInput(event, key) {
    let capsText = event.target.value
      .toLowerCase()
      .split(' ')
      .map(s =&amp;gt; s.charAt(0).toUpperCase() + s.substr(1))
      .join(' ');

    this.setState({
      [key]: capsText
    });
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That's it! Not so bad, eh?&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>react</category>
      <category>forms</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
