<?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 Kahlia Pinkins on Medium]]></title>
        <description><![CDATA[Stories by Kahlia Pinkins on Medium]]></description>
        <link>https://medium.com/@kpinkin1?source=rss-e6ca763ab06d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ESiaHSJVzto-0b-nXDQoRA.jpeg</url>
            <title>Stories by Kahlia Pinkins on Medium</title>
            <link>https://medium.com/@kpinkin1?source=rss-e6ca763ab06d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:23:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kpinkin1/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[Data Cleaning using Python’s Pandas]]></title>
            <link>https://medium.com/@kpinkin1/data-cleaning-using-pythons-pandas-a5df4b36a561?source=rss-e6ca763ab06d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5df4b36a561</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[pandas-functions]]></category>
            <dc:creator><![CDATA[Kahlia Pinkins]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 13:26:39 GMT</pubDate>
            <atom:updated>2023-12-17T13:26:39.047Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a guide to data cleaning in Python’s Pandas. We will see the process and how to apply Panda’s methods to any dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XBE3mQqWb4WWNl-eN72Zw.png" /><figcaption>RealPython.com</figcaption></figure><p>Data is everywhere that we go. Every time someone creates a new account or fills out a form online, that data is being stored somewhere. There is data on every topic imaginable: bike sales, Covid-19 statistics, basketball fan behavior, cancer patient survival rates, anything you can think of. There are several sites where we can find data readily available to be manipulated and to tell a story. We can use that data to analyze global trends, influence life-changing decisions, predict world-altering events, the possibilities are endless. But how can we do this? We start at the beginning by cleaning the data.</p><h4>Why we need to Clean Data</h4><p>Data cleaning is one of the most important (and one of the most time-consuming) part of working with and manipulating data. Data is useless if you are unable to understand and use it in a clear and meaningful way. Say you have a table that identifies Lebron James as the US basketball fans’ favorite player, but his name shows up in different ways: some called him “LJ”, while others listed him as “Bron”, and a few put his name as “lebron Jams”. Even though we are referring to the same player, it would be impossible to show this in any meaningful way because it is not clear that all of these people are speaking about just one person. That’s where we come in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eZ8F46e_Qya7F_YHks1YQ.png" /><figcaption>learnenough.com</figcaption></figure><p>We can clean the data, parsing through and changing every odd reference to Lebron James into a single, uniform name. This will allow anyone looking at the data and even further, any software looking at the data, to recognize that all of these values are referring to one single basketball player and therefore be able to see the true volume of people who picked him as the best. There are SEVERAL ways that our data can be messy, which means there are SEVERAL ways that our data can be cleaned. I’m going to be showing you the top ways that I use Python’s Pandas to create a uniform and clean dataset.</p><h4>Handling Duplicate Values</h4><p>The first thing that I normally do in any given dataset that I find is handling the duplicate values. Duplicate values are usually full rows in your column that are exactly the same (or column values that are meant to be unique showing up in multiple rows of your dataset). In Python, there is a method for quickly and seamlessly dropping duplicate values:</p><pre># Drops all the duplicate values in our DataFrame<br>df.drop_duplicates()</pre><p>This method drops all of the duplicate values from our dataframe, and if you enter a parameter “subset”, you can drop the duplicates from specific columns where the values are meant to be unique:</p><pre># Drops all the duplicate values in our unique_column<br>df.drop_duplicates(subset=[&quot;unique_column&quot;])</pre><h4>Handling Irrelevant Columns</h4><p>Part of cleaning your data is determining what’s important to your analysis and what isn’t. Usually, when pulling in huge data sets, we’ll have columns that we don’t need in order to carry out our analysis. Luckily for us, there is a way to get rid of all of the unwanted columns and only use the data that we need. We can do this using the drop keyword:</p><pre># Deletes all columns listed as unwanted columns<br>df.drop(columns=[unwanted_columns])</pre><p>With this method, we can drop all the columns we no longer want as a single list in our columns parameter.</p><h4>Creating Uniform Data Types</h4><p>Often times in our dataset, we are getting the same information, but in several different formats. For example, there could be a single column called start_date where the dates are in several forms. Some rows list the date in the format December 20, 2022, others as 20–12–2022, and some have 12/20/22. All of these dates are referencing the same day, but they are in completely different formats. The same can happen if say a numeric value is appearing in your dataset as a string or vice-versa. This type of data can prevent us from being able to observe the data in a meaningful way, so Pandas has given us a few simple solutions to handling this:</p><p>to_datetime() — : Changes column into datetime format.</p><pre># Convert one column to datetime.<br>pd.to_datetime(df[column_name])</pre><p>astype(‘int’) — : Changes column into int format.</p><pre># Convert one column to int.<br>df[&#39;col_1&#39;].astype(&#39;int&#39;)<br><br># Convert multiple columns to int.<br>df.astype({&quot;col_1&quot;:&quot;int&quot;,&quot;col_2&quot;:&quot;int&quot;})<br><br># Convert all columns to int.<br>df.astype(&#39;int&#39;)</pre><p>to_string()/as_type(str) — : Changes column into string format.</p><pre># Convert one column to string.<br>df[column].to_string()<br><br># Convert all columns to string.<br>df.astype(str)</pre><p>astype(float) — : Changes column into float format.</p><pre># Convert one column to float.<br>df[&#39;Fee&#39;].astype(float)<br><br># Convert multiple columns to float.<br>df.astype({&#39;col_1&#39;:&#39;float&#39;,&#39;col_2&#39;:&#39;float&#39;})<br><br># Convert all columns to floats.<br>df.astype(float)</pre><p>As you can see there are several ways to change the datatypes of your columns in Pandas. While there are many more, I use these the most frequently and these work for me!</p><h4>Handling Missing Values</h4><p>Another important part of cleaning your data properly is knowing how to handle missing values. Unfortunately not all datasets are complete, in fact, most datasets aren’t, and it is our job to identify what we should do when there are missing values within our rows or columns. The most common ways to handle missing values are to (1) Fill it with a value that means something to us or (2) Delete the rows with the missing values. Pandas knows this and provides us with simple ways to do both!</p><p><strong>Finding missing values</strong> — If you’re dealing with a dataset that has thousands or hunderds of thousands of rows, chances are that you may not be able to check every row with missing data. There are two main ways that you can filter your data to show you where the missing data lies in your dataset:</p><p><strong>Finding <em>columns</em> with missing values</strong> — Here we can check for which columns in our dataset have missing values:</p><pre># Filters df to only the columns that contain null or missing values<br>df.columns[df.isnull().any()]</pre><p><strong>Finding <em>rows</em> with missing values </strong>— Here we can check for which rows in our dataset have missing values:</p><pre># Filters df to only the rows that contain null or missing values<br>df[df.isnull()]</pre><p>If you don’t understand the logic of these two, don’t fret, this is part of filtering our data, which I will cover in another article coming up soon!</p><p><strong>Filling in missing values</strong> — You can fill in all missing values with some other meaningful value. For numeric values, you may choose 0, or an average or median of the other values within the given column. For categorical values, you may choose to call the missing values “Unknown” or fill it in with the most common likely choice of a given column. In Pandas you can do all of this with fillna:</p><pre># Fills all missing values in df with &quot;Unknown&quot;.<br>df.fillna(&quot;Unknown&quot;)<br><br># Fills missing values in single column with 0.<br>df[&#39;col_1&#39;].fillna(0) </pre><p><strong>Deleting missing values</strong> — Sometimes data with missing rows needs to be deleted. If the row is meaningless without the data in those particular columns, then it’s best to just drop those rows and stick with the data that can provide us insights on what we need to analyze. In Pandas, a simple way to get rid of rows with missing data is dropna:</p><pre># Deletes all missing values in df.<br>df.dropna()<br><br># Deletes all missing values in single column.<br>df[&#39;col_1&#39;].dropna()</pre><h4><strong>Dealing with Structural Errors</strong></h4><p>There are several ways that we can have structural errors in our dataset. If something is misspelled, if there are extra spaces in our data, if some words are capitalized and others are not, if something is formatted in a way that we don’t want, etc. There’s simply no way to know the exact errors that your dataset is going to have but I’m going to provide you with 4 very popular ways to get your columns more uniform and hopefully the rest will come easily.</p><p><strong>Title</strong> — It is common in columns such as a name or place column, to capitalize every first letter in a sentence, with every other letter being lower case. I love to do this to my datasets to create uniformity, especially when it comes to name and location fields. Luckily for me, in Pandas there’s an easy way to do this with a method called .title():</p><pre># Converts first character of each word in column<br># to uppercase and remaining to lowercase.<br><br>df[&#39;col_1&#39;].str.title()</pre><p>Keep in mind that you can also create uniformity using .upper(), .lower(), .capitalize(), and .casefold(), but my favorite and the one that I use most frequently is .title().</p><p><strong>Strip</strong> — Sometimes we have columns that have unwanted spaces and characters, either in front, at the end, or in the middle of them. Strip allows us to get rid of the unwanted spaces and characters. If we don’t specify, it simply gets rid of the unwanted white space, but if we specify which characters we want to delete, Pandas will get rid of all characters within the given string:</p><pre># Gets rid of trailing white spaces<br>df[&#39;col_1&#39;].str.strip()<br><br># Gets rid of any characters to the left of the string containing<br># 1, 2, 3, or .<br>df[&#39;col_2&#39;].str.lstrip(&#39;123.&#39;)<br><br># Gets rid of any characters to the right of the string containing<br># a new line, tab, space, or comma<br>df[&#39;col_2&#39;].str.lstrip(&#39;\n\t ,&#39;)</pre><p><strong>Replace</strong> — Remember our example from earlier, where Lebron James had several different values given as his name such as “LJ”, “Bron”, and “lebron Jams”? This is where replace comes in handy! The Pandas replace function allows us to replace one or more given values with another value. Here’s how it works:</p><pre># Syntax:<br>df.replace(old_value, new_value)<br><br># Example: Replaces all values of 100 with 500<br>df.replace(100, 500)<br><br># Replace one element with one value<br># Example: Replaces all instances of &quot;LJ&quot; with &quot;Lebron James&quot;<br>df[&#39;player_name&#39;].replace(&quot;LJ&quot;, &quot;Lebron James&quot;)<br><br># Replace multiple elements with one value<br># Example: Replaces all instances of &quot;LJ&quot;, &quot;Bron&quot;, and &quot;lebron Jams&quot; with &quot;Lebron James&quot;<br>df[&#39;player_name&#39;].replace([&quot;LJ&quot;, &quot;Bron&quot;, &quot;lebron Jams&quot;], &quot;Lebron James&quot;)<br><br># Replace muliple elements with multiple values<br># Example: Replaces all instances of &quot;LJ&quot; with &quot;Lebron James&quot;<br># &amp; all instances of &quot;SC&quot; with Steph Curry&quot;<br>df[&#39;player_name&#39;].replace([&quot;LJ&quot;, &quot;SC&quot;], [&quot;Lebron James&quot;, &quot;Steph Curry&quot;])</pre><p><strong>Apply </strong>— Sometimes we want to do a specific function to our dataframe or column, but that function isn’t present in Pandas. For example, let’s say I have a dataframe where I want to create an age range for my data, rather than individual ages. This may be hard to do if we have to loop through every single row and check which age range it should be assigned to. This type of problem is perfect for the .apply() method! In this method, we can pass any function we create to our dataframe column(s) and the results will be applied to every single row:</p><pre># Syntax:<br>df[column_name].apply(function_name)<br><br># Example: Creates age range for all values in &#39;age&#39; column<br><br>def create_age_range(age):<br>  if age &gt; 40:<br>    return &quot;over 40&quot;<br>  else:<br>    return &quot;under 40&quot;<br><br>df[&#39;age&#39;].apply(create_age_range)</pre><p>As you can see, even when Pandas doesn’t have a specific method or function for our problem, we can create one and apply it to our data frame ourselves!</p><h4>Conclusion</h4><p>We’ve gone over several Pandas methods that make life easier when it comes to data cleaning. Now that we have these tools in our arsenal, we can apply them to every new data set that we get. Are we done cleaning our data? Pretty much. Is our data ready for analysis? Not quite. Next we need to check the trends of our data, filtering and querying to see what we’ve missed and what looks strange. I will be going over this process in another article, so stay tuned for that and happy cleaning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5df4b36a561" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to SQL for Beginners: Creating a Database]]></title>
            <link>https://towardsdev.com/a-comprehensive-guide-to-sql-for-beginners-creating-a-database-fc6f7205235e?source=rss-e6ca763ab06d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6f7205235e</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[rdbms]]></category>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kahlia Pinkins]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 20:06:58 GMT</pubDate>
            <atom:updated>2023-12-14T17:11:56.846Z</atom:updated>
            <content:encoded><![CDATA[<p>So, you’re in a bind and need to learn everything you can about SQL and fast… Maybe you have an interview coming up where you <em>may</em> have exaggerated your skillset a smidge or you went to one too many parties to study for that SQL final that’s going to be 50% of your grade. Well have no fear… your SQL guru (yes, me) is here to help. I am going to take you from zero to hero in SQL and you’ll be showing off those coding chops in time for that test!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*eO7qtqUrNlHDPWhZM9lKfA.jpeg" /><figcaption>Source: Gallery Systems</figcaption></figure><h3>Outline</h3><p>In Part One of this series, we are going to be going over the very basics of creating an SQL database. We need to know all of SQL’s functionalities before we can move on to more advanced topics. Here’s what you’ll know after finishing this article:</p><ul><li>RDBMS</li><li>SQL Commands</li><li>Data Types</li><li>Primary &amp; Foreign Keys</li><li>Constraints</li><li>Creating, Modifying, &amp; Deleting Tables</li><li>Creating, Modifying, and Deleting Records</li></ul><p>This article will give you an introduction into all of these simple topics in creating an SQL database so that you can later learn how to script in SQL like a pro!</p><h3>RDBMS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*seZAfqawSxjml8a8ntrOVA.jpeg" /><figcaption>Source: Nirupa Vijayakumar</figcaption></figure><p>If you’ve ever been in the world of tech, you’ll here this acronym thrown around constantly. Usually when it comes to random acronyms, I just try to smile and nod along, but RDBSM is something that you’ll want to know like the back of your hand in any SQL interview or test. RDBMS stands for Relational Database Management System. Now you’re thinking “what is that? That sounds complicated and confusing.” It’s actually quite simple. A Regional Database Management System is basically any system that holds data in the form of tables with rows and columns rather than any other form. There are several other forms of DBMS (Database Management Systems) because there are several other ways that data can be stored and managed, but all <em>you</em> have to remember is that RDBMS hold tables to organize its data. That’s it. Some good examples of RDBMS are MySQL, PostegreSQL, and Oracle.</p><p>Now you’re asking “well, what does this have to do with SQL? Is SQL a RDBMS?” Well… not exactly. SQL is essentially the only language that a RDBMS can understand. If we need to retrieve something from a table in our RDBMS, we need to ask for it. How can we ask? Using SQL. We want to be able to communicate with any RDBMS so that we can create, retrieve, update, and delete any of the data within the RDBMS with ease. This is the purpose of SQL and learning it will change the way that you see data forever.</p><h3>SQL Commands</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*RHOq6imhLSyWQJ7II_xP4A.jpeg" /></figure><p>This is a very broad topic so I’m going to teach you the most fundamental commands and build on it later. First, what is an SQL command? An SQL command is just an action that you want your RDBMS to perform in order to create, retrieve, update, or delete some data in your database (table or set of tables). Here are some of the most important commands in SQL:</p><ul><li>SELECT — A SELECT command is to retrieve some specific data from the database</li><li>CREATE TABLE— The CREATE TABLE command creates a new table in our database</li><li>ALTER TABLE — The ALTER TABLE command is to modify or update a table in our database</li><li>DROP TABLE — The DROP TABLE command deletes a table from our database</li><li>INSERT INTO — The INSERT INTO command inserts data into one our our tables</li><li>UPDATE — The UPDATE command is used to modify or update data in one of our tables</li><li>DELETE FROM — The DELETE FROM command deletes data from one of our tables</li></ul><p>These commands are the building blocks of SQL, you will use these again and again in any SQL code that you create, so make sure to get really familiar with these commands and what they do.</p><h3>Data Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*J3FJzr0DiDJGnuhUXd46xA.png" /></figure><p>Each column in any of our tables in our database has something called a data type. This is exacly what it sounds like: the type of data that we want our column to hold. Data types are used to categorize the data in our database so that we can keep our database organized. The most common data types in SQL are:</p><ul><li>INT — INT is short for integer and refers to any integer value</li><li>DECIMAL(M,N) — DECIMAL is a number with a decimal point where M is the maximum total number of digits and N is the maximum total number of digits after the decimal</li><li>VARCHAR(N) — This is a string of text that must always be in quotes, where N is the maximum number of characters</li><li>BLOB — This is a Binary Large OBject, it basically refers to large amounts of data i.e images and files</li><li>DATE — A date formatted as ‘YYYY-MM-DD’</li><li>TIMESTAMP — A date &amp; time formatted as ‘YYYY-MM-DD HH:MM:SS’</li></ul><p>When creating a table or a column in a table in the database, we must indicate what kind of data we are inserting into our table. This way all of our data is formatted, clean, and the RDBMS can recognize the funtions that each column can and cannot perform.</p><h3>Creating a Table</h3><p>Now that we know the command to create a table and we know that we need to indicate which data types are going into our table, we can finally attempt to <em>create</em> a table in our database. Let’s create a table called “student”. Here’s how:</p><pre>CREATE TABLE student(<br>  name VARCHAR(20),<br>  age INT<br>);</pre><p>Okay, let’s break this down. Here we used the command CREATE TABLE to create a table in our database, we gave it a name which is “student”, and we added two columns. The first column is called “name” and it can hold data in the form of a VARCHAR element (string of text) that can have up to 20 characters. The second column is called “age” and it can hold data in the form of an INT (any integer value).</p><p>Let’s create another table called “professor” that has 2 columns: a “name” column and a “startdate” column:</p><pre>CREATE TABLE professor(<br>  name VARCHAR(20),<br>  startdate DATE<br>);</pre><p>Here we used the command CREATE TABLE again to create a table called “professor”. We added a “name” column which can hold VARCHAR elements up to 20 characters and a “startdate” column which can hold a date in the form of ‘YYYY-MM-DD’.</p><p>Great! We’ve created the first tables in our database, the “student” table and the “professor” table.</p><h3>Primary Keys</h3><p>So, we’ve created our student and professor tables and are ready to add data into them, right? Not just yet. There is still something important that we need to consider first. What if we have two students with the same name and age? Certainly, stranger things have happened. How do we tell them apart in our database? That’s a great question and the answer is simple, with the PRIMARY KEY!</p><p>A PRIMARY KEY refers to a column that uniquely identifies each record (row) in our table. This can be a trivial value, or it can be something significant that represents the record in the real world, like a SSN. Really it is just a unique identifier of each row, so that even if all other values are the same, the database can still set each record apart. To indicate that a column will hold the PRIMARY KEY, you <em>must</em> put the PRIMARY KEY keyword after declaring the column name and type.</p><p>So, let’s delete our previous tables and recreate them with a primary key.</p><pre>DROP TABLE student;<br>DROP TABLE professor;<br><br>CREATE TABLE student(<br>  student_id INT PRIMARY KEY,<br>  name VARCHAR(20),<br>  age INT<br>);<br><br>CREATE TABLE professor(<br>  professor_id INT PRIMARY KEY,<br>  name VARCHAR(20),<br>  startdate DATE<br>);</pre><p>First in our code, we used the DROP TABLE command to delete the student and professor tables that we created before. Then we used the CREATE TABLE command again to recreate them with the columns that we want.</p><p>We’ve created 2 tables called student and professor where the student table has a PRIMARY KEY called “student_id” which is an integer value, and the professor table has a PRIMARY KEY called “professor_id” which is also an integer value.</p><p>Note: You can also declare your PRIMARY KEY after all of the columns are set. For example:</p><pre>CREATE TABLE student(<br>  student_id INT,<br>  age INT,<br>  PRIMARY KEY(student_id)<br>)</pre><h3>Constraints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*R_0JROr5lBBs5DoDCMsvpQ.png" /><figcaption>Source: Coding Ninjas</figcaption></figure><p>A constraint is something that you add to your table when you want one or more columns to adhere to specific rules. For example, PRIMARY KEY is a constraint. If a column is made to be a primary key, it must be unique and it cannot be empty. This is because it is the unique identifier of the record. If you try to add a record where the primary key does not adhere to these rules, an error will be indicated in your code. Constraints help the DBMS identify the rules and boundaries that each column must adhere to. Here is a list of important constraints:</p><ul><li>NOT NULL — allows us to define that a particular column in the table cannot be empty aka NULL</li><li>UNIQUE — allows us to define that a particular column in the table cannot have duplicate entries</li><li>DEFAULT — allows us to add a default value if nothing is specified</li><li>AUTO_INCREMENT- automatically increments a value with every additional table entry</li></ul><p>If we wanted to create a table to demonstrate how constraints work, we could create this table called “courses”:</p><pre>CREATE TABLE courses(<br>  id INT PRIMARY KEY,<br>  course_name VARCHAR(20) UNIQUE NOT NULL,<br>  textbook VARCHAR(40) DEFAULT &#39;Basic&#39;<br>);</pre><p>Let’s break this down. Here we created a table called courses. The first column is called “id” and holds the primary key. The second column, “course_name” is a VARCHAR and has two constraints. “course_name” is both unique <em>and</em> not NULL. The third column is called “textbook”, if no value is added in that field, the value will be filled in as “Basic”.</p><p>Constraints are extremely useful to specify what rules we want our data to follow in our database!</p><h3>Inserting Data into a Table</h3><p>Now that we have completed our tables, we can add data to them in the form of rows or records. Let’s add a record to our “student” table.</p><pre>INSERT INTO student VALUES(1, &#39;Harry&#39;, 11);</pre><p>Here, using the INSERT INTO command, we have inserted the values 1 as the “student_id”, Harry as the “name”, and 11 as the “age”.</p><p>If we want to insert several records into our table, we can do so by adding more groups of values separated by a comma, like this:</p><pre>INSERT INTO student VALUES<br>  (2, &#39;Ron&#39;, 11),<br>  (3, &#39;Hermione&#39;,11),<br>  (4, &#39;Percy&#39;, 16);</pre><p>We’ve now added 4 different records into our student table. When we retrieve it using our SELECT command (more on this later), it should look like this:</p><pre>SELECT *<br>FROM student;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37vlPjHZDy1jyW2vplrMpQ.png" /></figure><p>Here we used the SELECT command to retrieve our data. We won’t be going over the SELECT statement in this part of our series, but just know that the * indicates that all data will be retrieved FROM the table specified. From now on, any time I show a table, I’m using the SELECT command to retrieve the data.</p><p>We can also signify that we only want to add values into specific columns. Let’s see how using our “courses” table:</p><pre>INSERT INTO courses(id,course_name) VALUES (203, &#39;Potions&#39;);</pre><p>If you recall from the last section, our “courses” table has a column called “texbook” which has a DEFAULT constraint. If we don’t specify a value for “textbook”, SQL will add the default value, which is written as “Basic”. In the code above, we used the INSERT INTO command to <em>only </em>add values to the “id” and “course_name” fields. Our “courses” table should look like this after running the code above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAMn8vpzWlUP6-aL2En7mw.png" /></figure><h3>Deleting Data from our Table</h3><p>Let’s say, we only want first years in our student table. We know that all first years are 11 years old. That means we can delete <em>any</em> records from the student table where the age <em>is not equal to</em> 11. Note that in SQL, the symbol for “is not equal to” is “&lt;&gt;”. We can do this by using the DELETE FROM command, and a keyword we haven’t seen yet called WHERE.</p><pre>DELETE FROM student WHERE age &lt;&gt; 11;</pre><p>As you can see above, the WHERE keyword specifies a condition. We use the WHERE keyword when we want to tell our DBMS to do our command <em>only</em> to the records from the table that follow a specific condition. When we run this code, it will delete all of the records from student table WHERE the age is not equal to (&lt;&gt;) 11.</p><h3>Altering our Table</h3><h4>Deleting Columns</h4><p>There are two very important ways to alter a table: to add columns and to delete columns. Let’s take a look at deleting a column first. We previously deleted all of the records in our “student” table where the age was not equal to 11. Now that we have a table with only first year students, and we know that each of the students is 11 years old, the age column seems a bit redundant. Let’s get rid of it:</p><pre>ALTER TABLE student DROP COLUMN age;</pre><p>Here we have the ALTER TABLE command paired with a (new) DROP COLUMN command. When we run this, the “age” column is deleted. Now we have a table with just the remaining columns, “student_id” and “name”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrwgIFY7AbOXDgLx-d8Y_g.png" /></figure><h4>Adding Columns</h4><p>Now let’s take a look at adding a column to our table. Say we want to indicate who our student’s homeroom professors are. We <em>could</em> add a “professor_name” and “professor_startdate” column to the student table to show who each student’s professor is. But that’s a bit unnecessary, isn’t it? If you recall, we already have a professor table with that information in it. If we want to find out specific data about a professor, we should <em>only</em> be refering to the professor table. How then, can we succinctly identify which professor is for which student? By using the “professor_id” of course! This is the unique identifier of each professor in our database; we can use that to refer to the correct professor and look up more information in the professor table later if we need to. Let’s add a column for “professor_id” in our student table:</p><pre>ALTER TABLE student ADD professor_id INT;</pre><p>Once we run this, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYTF1-ev6tWxkLweDJoqtA.png" /></figure><p>Notice that the value is NULL for “professor_id” in each student record. This means that there is no value listed in that column for a particular record. Our “professor_id” was created <em>after</em> the student table already had 3 records, so we have no values in the “professor_id” column yet. Before we can populate that column in our student table, we must create some professor records.</p><h3>Foreign Keys</h3><p>A foreign key refers to a column which references another table’s primary key. This is exactly the situation that we’ve just created. In the table above, the student table has a “professor_id” column which we would like to reference the “professor_id” column in our professor table. Before we can add any values to “professor_id”, we’ll need to create some professor records, so that we can know which professors our student table is referencing. Let’s add 3 professors:</p><pre>INSERT INTO professor VALUES<br>  (101, &#39;Snape&#39;, &#39;1981-09-01&#39;),<br>  (102, &#39;Hagrid&#39;, &#39;1993-07-15&#39;),<br>  (103, &#39;McGonagall&#39;, &#39;1956-12-01&#39;);</pre><p>Here’s our professor table now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joHC4P7_zmpdWubp25Pxpg.png" /></figure><p>Now that we’ve added professors to our professor table, we can populate our “professor_id” column in our student table. Before we do that though, we want to indicate to our DBMS that our student “professor_id” is refering to the professor “professor_id”. To do this, we need to add a foreign key to our student table. Take a look:</p><pre>ALTER TABLE student <br>ADD FOREIGN KEY (professor_id) <br>REFERENCES professor(professor_id)<br>ON DELETE SET NULL;</pre><p>Let’s break this down:</p><ol><li>Line 1 — We are using the ALTER TABLE command to let the DBMS know that we are altering the student table.</li><li>Line 2 — We are using the ADD FOREIGN KEY command to indicate that the “professor_id” in the student table is a foreign key.</li><li>Line 3 — We are using the REFERENCES keyword to say that the foreign key is referencing the “professor_id” column in the professor table.</li><li>Line 4 — ON DELETE SET NULL tells the DBMS that if the reference record is deleted from the professor table, it should set the corresponding student records to NULL in the “professor_id” column.</li></ol><p>After letting the DBMS know that the student table’s “professor_id” column is a foreign key, we can then populate it.</p><h3>Updating Records</h3><p>We want to update our “professor_id” column in our student table for each record. Let’s say Harry and Ron have Snape as a professor. We know that Snape’s id is 101, so lets add that value to our “professor_id” field for Harry and Ron:</p><pre>UPDATE student<br>SET professor_id = 101<br>WHERE student_id &lt; 3;</pre><p>Let’s analyze this code together:</p><ol><li>Line 1 — We use the UPDATE keyword when we want to modify a record or records in a table. In this case we are updating our student table.</li><li>Line 2 — The SET keyword lets the DBMS know what value you want to change in your table. In our case, we want the “professor_id” to be equal to 101.</li><li>Line 3 — Here’s that WHERE keyword again. The WHERE keyword specifies what conditions the records need to meet for the previous command to apply. This WHERE statement is letting us know that any record with a “student_id” that is <em>less than</em> 3 (i.e. 1 and 2 for Harry and Ron) will set their “professor_id” to 101.</li></ol><p>Here’s what we get after running this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGL7YithlMx-vLFi3i_w-A.png" /></figure><p>Let’s add McGonagall as Hermione’s professor.</p><pre>UPDATE student<br>SET professor_id = 103<br>WHERE student_id = 3;<br><br>SELECT *<br>FROM student;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdeBcFeyJpJXKVJSPyiKuQ.png" /></figure><h3>Conclusion</h3><p>We have succesfully created a database! We went from knowing no SQL to now knowing what a relational database management system is, how SQL fits in, what goes into creating a database, and how to create, modify, and delete tables and records within our database! We created 3 tables in our database, added constraints and primary keys, and connected some of them through the use of foreign keys. I encourage you to play around with these concepts! You can add more records to each table, add another foreign key to the student table referencing the courses table, add another table which is a combination of two existing tables. The possibilities are endless!</p><p>Now I know that you’re dying to know how to retrieve all of the data that I showed you in this tutorial in a dynamic way, you’re asking yourself what is SELECT * and why did she have me use that every time I wanted to look at my tables. Fear not! I will explain everything in the next install of this SQL series called “A Comprehensive Guide to SQL for Beginners: Queries.” Master creating a database first, and stay tuned for the next install of this series! Happy coding!</p><h3>Acknowledgements</h3><p>I want to thank two majorly important helpers in my journey creating this article. First, I need to thank TechTFQ on YouTube for giving me all of the guidelines for what needs to be learned from beginning to end in SQL. His video was an incredible help to me in creating the outline for this article and the articles to come and I highly recommend watching it to get a sense of what you need to learn at which stage while learning SQL. Secondly, I’d like to thank freeCodeCamp.org. I took quite a bit of inspiration for the material in this article from them and I would be remiss not to include their information in this article. Find the videos that helped me along the way below, and be sure to check them out if you’re a more hands-on learner!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fa-hFbr-4VQQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Da-hFbr-4VQQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fa-hFbr-4VQQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b8c3aeef7a47240878ba3d217d5d1d0/href">https://medium.com/media/4b8c3aeef7a47240878ba3d217d5d1d0/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHXV3zeQKqGY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHXV3zeQKqGY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHXV3zeQKqGY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e539c6226ce6d23e2947089ea34ae55/href">https://medium.com/media/0e539c6226ce6d23e2947089ea34ae55/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6f7205235e" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/a-comprehensive-guide-to-sql-for-beginners-creating-a-database-fc6f7205235e">A Comprehensive Guide to SQL for Beginners: Creating a Database</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Dynamic React App]]></title>
            <link>https://javascript.plainenglish.io/how-to-create-a-dynamic-react-app-49e02d303436?source=rss-e6ca763ab06d------2</link>
            <guid isPermaLink="false">https://medium.com/p/49e02d303436</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Kahlia Pinkins]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 08:46:44 GMT</pubDate>
            <atom:updated>2022-03-15T06:39:29.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide on creating a dynamic React app.</h4><p>So… you want to build an app that can be easily navigated both by users and developers, with elements that can be re-used anywhere you want in your code, and is simpler both to code and to understand? Seems impossible, right? Maybe we are truly forever doomed to hand-select each and every element on the DOM and modify it endlessly until perfect. Or maybe, we can just try React.</p><h3>What is React?</h3><p>I’m glad you asked! React is a development library created by Facebook which allows developers to break their code up into bite-sized, reuseable chunks called <em>components. </em>Components are created separately and are then put together to create a dynamic and fully functioning application. Here’s a visualization of React components and how they work together to build an app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*TdI0YTnpoB3mb6S-7NJrMw.jpeg" /><figcaption>React Components Visualization. Source: <a href="https://www.techdiagonal.com/">https://www.techdiagonal.com/</a></figcaption></figure><p>Illustrated here are four components which are then put together to create an entire app. Notice that some of the components are used more than once in our application. This is what makes React so useful! We can use each component several times in our application without rewriting the code.</p><p>Each component is created by using a capitalized function that returns JSX which looks conveniently similar to HTML:</p><pre>function Component(){<br>  return(<br>    &lt;h2&gt;Hello World&lt;/h2&gt;<br>  )<br>}</pre><p>If we want to then declare our component elsewhere in our application, we would write:</p><pre>&lt;Component /&gt;</pre><p>React allows us to return code that is nearly identical to HTML (JSX), making our code both easier to write and easier for other developers to read and understand. In the application that I recently created using React, I have several components which all work together to create my application in its final form. Let’s identify some of the components that I added to my application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYOUJbB3IeFR1xP4TEGjkA.png" /><figcaption>A screenshot of my React application</figcaption></figure><p>Can you count how many components are being displayed in this one snippet of my anime application? I count 4. The Nav Bar, Search Bar, Sort Bar, and Title Card are each individual components with their code. Breaking my app up into separate components allows me to more easily focus on the separate functions of each part of the app. Combining components into a singular app using React syntax looks something like this:</p><pre>function App(){<br>  return(<br>    &lt;div&gt;<br>      &lt;NavBar /&gt;<br>      &lt;Search Bar /&gt;<br>      &lt;SortBar /&gt;<br>      &lt;TitleCard /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Here, we are combing all our components into one singular App component to create a whole application!</p><p>So we’ve learned about React and components and why they’re incredibly useful, but we’re missing a huge piece of the puzzle! Now that we know that React components <em>return </em>JSX which looks quite similar to HTML, we want to know what React components <em>accept </em>as arguments to make these components so dynamic.</p><h3>Props</h3><p>What are props and what are they useful for in React? Put quite simply, props are the arguments that are passed down to React components. Props are passed down as attributes, much like in HTML. They allow us to pass down different values to the same component and get still get a different result. Let’s look at an example from my React application:</p><pre>function AnimeCard({ <strong>anime </strong>}){<br>   return(<br>        &lt;div &gt;<br>            &lt;h2&gt;{anime.title}&lt;/h2&gt;<br>            &lt;img src={<strong>anime</strong>.<strong>image</strong>} alt={<strong>anime</strong>.<strong>title</strong>}/&gt;<br>            &lt;button&gt;&#39;🤍 Favorite&#39;&lt;/button&gt;<br>            &lt;button&gt;&#39;More Info...&#39;&lt;/button&gt;<br>        &lt;/div&gt;<br>}</pre><p>The prop being passed down here is called anime, which is declared in a parent component. You may notice that there are brackets around {anime.title} whenever we use it in our return function. When we want to return Javascript rather than JSX in a React component, we need to indicate that it is Javascript so that React can turn it into JSX for us. Notice that we can pass whatever anime object we want to this code as long as it has a title and image key. We can therefore use this component anywhere in our code, pass down an anime object with title and image keys, and a card will render on the page for us displaying the data that we passed down. Here’s what it looks like to pass down a prop:</p><pre>const anime1 = {<br>  title: &#39;Attack on Titan&#39;,<br>  image: &quot;AOT.jpeg&quot;<br>}</pre><pre>const anime2 = {<br>  title: &#39;Demon Slayer&#39;,<br>  image: &quot;DS.jpeg&quot;<br>}</pre><pre>&lt;AnimeCard <strong>anime={anime1}</strong>/&gt;<br>&lt;AnimeCard <strong>anime={anime2}</strong>/&gt;</pre><p>Note that we also put brackets around our declared anime variables here, because we are passing Javascript to a JSX component. This code will render something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*LK63I3vBgJcsdX4TSvW1_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*Qjna2Q2xCFnRNBVYuSLK5A.png" /><figcaption>Card Components from my react application</figcaption></figure><p>Here we can see that the same card component was able to be used more than once in my application with different data on each card because of the use of props. Props can be extremely useful in our components, as we can pass nearly anything down as a prop, even functions!</p><h3>Events</h3><p>Now, we know how to create a basic app with React, but as we all know from my last post, the more interactive an app, the better it is! We should be listening for several events to increase our user’s experience and engagement! But how can we do this? We know how to listen for events in vanilla Javascript, by pinpointing the DOM element and adding an event listener to that element, but what if I told you that all of that pinpointing is a thing of the past? All we need to do to detect an event in React is add a simple keyword in front of the event we’re looking for: ‘<em>on</em>’. If we use an onClick listener, we know that our JSX element should react when clicked; if we use an onChange listener, then it should react when changed; the same goes for onSubmit, onLoad, and any other event that takes place on the page. Let’s take a look at a change event listener I added to the search bar in my react application:</p><pre>&lt;input className=&quot;search&quot; type=&quot;text&quot; placeholder=&quot;Search...&quot; value={input} <strong>onChange={handleChange}</strong>&gt;&lt;/input&gt;</pre><p>Here, I am adding an<em> onChange </em>event to my &lt;input&gt; tag, so that every time the field is changed (i.e. another letter is typed or erased), the function handleChange is called. We see here that react provides a very simple way for us to add event listeners to our JSX elements.</p><p>However, that’s not all that React does for us with regard to adding dynamic and change to our apps. React has also provided us with a wonderful function called <em>State</em>.</p><h3>State</h3><p><em>State </em>is data that changes throughout time as users interact with your app. In our example up above, we would want our input value to be a State value because it changes every time someone types in our form. Let’s look at an in-depth example to understand the State better. In order to have access to State, we need to import it from react and declare it in our React component:</p><pre>import React, <strong>{ useState }</strong> from &#39;react&#39;;</pre><pre>function Search({ animes }){<br>  <strong>const [input, setInput] = useState(&#39;&#39;);</strong></pre><pre>// ...<br>}</pre><p>Let’s break this code down. We can see that { useState } is being imported from React. We must import this to use state in our code. Next, let’s look at our variable declaration. We see that there is an array with a variable called <em>input</em> and another variable called <em>setInput</em>. This is because State returns both a value (which is the value that you declare in the useState parentheses, in our case an empty string) and a function that is simply there to reset the value given when called. So right now we’ve set our <em>input </em>variable equal to an empty string, but if we call <em>setInput</em>, whatever we pass in as an argument will become our new <em>input </em>variable. Let’s keep going:</p><pre>function Search({ animes }){<br>  const [input, setInput] = useState(&#39;&#39;);</pre><pre>  <strong>const animeList = animes.filter((anime)=&gt;{<br>    return anime.title.toLowerCase().includes(input.toLowerCase())<br>   })</strong></pre><pre>   //...</pre><pre>}</pre><p>Here, we can see what we’re using our <em>input </em>variable for. We want to create a filtered anime list that only contains the animes where our title includes the <em>input </em>variable, i.e. what the user is typing. The big question then becomes, how can we change the anime list as often as the user types? That’s where <em>setState </em>comes in!</p><pre>function Search({animes}){<br>  const [input, setInput] = useState(&#39;&#39;);</pre><pre>  const animeList = animes.filter((anime)=&gt;{<br>      return anime.title.toLowerCase().includes(input.toLowerCase())<br>   })</pre><pre>   console.log(animeList);</pre><pre>   <strong>function handleChange(e){<br>      setInput(e.target.value);<br>    }</strong></pre><pre>   return(  <br>       &lt;input className=&quot;search&quot; type=&quot;text&quot; placeholder=&quot;Search...&quot;<br>        <strong>value={input}</strong> <strong>onChange={handleChange}</strong>&gt;&lt;/input&gt;<br>}</pre><p>Here, we can see that we are resetting our input variable every time the user types. The incredible thing about State is that every time it resets, the entire component re-renders, therefore re-running the anime list every time the user types, showing an up-to-date anime list with each letter typed! With the use of State and Event Listeners in our react application, we have everything that we need to create a dynamic and user-interactive application!</p><p>Here are just a few functions I was able to implement using React state:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fo7ySc1T5fKNH1XnRh9%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fo7ySc1T5fKNH1XnRh9%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fo7ySc1T5fKNH1XnRh9%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="215" frameborder="0" scrolling="no"><a href="https://medium.com/media/b12d1e010db66c3592d82c3004e349db/href">https://medium.com/media/b12d1e010db66c3592d82c3004e349db/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FKYmMGxE1QDKOCYhtTl%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FKYmMGxE1QDKOCYhtTl%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FKYmMGxE1QDKOCYhtTl%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="215" frameborder="0" scrolling="no"><a href="https://medium.com/media/c377db5451bd02115234fbad5e64ab46/href">https://medium.com/media/c377db5451bd02115234fbad5e64ab46/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FHxNM8AFwun9mLLgtRO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FHxNM8AFwun9mLLgtRO%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FHxNM8AFwun9mLLgtRO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="215" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb18a93511b299c7fa96f7be9c5af2e7/href">https://medium.com/media/eb18a93511b299c7fa96f7be9c5af2e7/href</a></iframe><h3>Client-Side Routing</h3><p>Amazingly, we’ve learned how to create a well-rounded web application with React components, props, events, and state. Now, all we need to worry about is that pesky little URL. You know the little text you put in the browser that navigates people to your exact website and site page? React apps were created in order to allow single-page applications. This means that our application need only use the initial GET requests along with our initial HTML, CSS, and JS. This makes a lot of things simpler, but we need a way to make sure that our URLs are reflective of the page (or component) that we want to show without having to refresh the page. Luckily, as with everything else, React makes this quite easy for us!</p><p>React gives us 3 main hooks that we can use to make our URLs effective for our use: Route, Switch, and NavLink. Let’s first discuss Route and Switch.</p><h4>Route and Switch</h4><p>Say we have a website called www.anime-app.com. We have 3 main components: Home, AnimeForm, and Favorites. Each of these components contains very different elements and we would like them to be featured separately. React gives us a way to navigate to a specific URL that displays only the component(s) that we’d like to show: the React hook <em>Route</em>.</p><pre><strong>import { Route, Switch } from &#39;react-router-dom&#39;;</strong></pre><pre>. . . . .</pre><pre><strong>&lt;Switch&gt;<br>    &lt;Route path=&#39;/submit&#39;&gt;</strong></pre><pre>        &lt;AnimeForm /&gt;</pre><pre><strong>    &lt;/Route&gt;</strong></pre><pre><strong>    &lt;Route path=&#39;/favorites&#39;&gt;</strong></pre><pre>        &lt;Favorites /&gt;</pre><pre><strong>    &lt;/Route&gt;</strong></pre><pre><strong>    &lt;Route path=&#39;/&#39;&gt;</strong></pre><pre>        &lt;Home /&gt;</pre><pre><strong>    &lt;/Route&gt;<br>&lt;/Switch&gt;</strong></pre><p>We see here that in order to use the <em>Route </em>hook, we have to import it from ‘react-router-dom’. We then need to wrap the components we want to be displayed on separate pages, in &lt;Route<em>&gt;</em> tags. In this example, the URL www.anime-app.com/<em>submit</em> will only display the <strong>AnimeForm </strong>component. Similarly, if we use the URL www.anime-app.com/<em>favorites</em>, only the <strong>Favorites </strong>component will show. If we were to use the URL www.anime-app.com<strong>/ </strong>we’d be taken to the application’s <strong>Home </strong>component. This ensures that if our user specifically wants to submit a form, they can go straight to the form through its URL, rather than having to start on the Home Page. But we aren’t quite finished.</p><p>We also need to wrap our Routes in &lt;Switch&gt; tags, which have been imported from ‘react-router-dom’, as well. Wrapping all of our Routes in &lt;Switch<em>&gt;</em> tags will make sure that none of these components render at the same time if they have the same characters (i.e. ‘/list’, ‘/list2’ won’t both be called if ‘/list’ is in our URL). React’s Switch hook checks the first path given and continues on until it finds a path that matches <em>any part</em> of the current URL. For example, if we were to move the Home path <em>before </em>the Submit path, the Home component would display no matter what; this is because its path (‘/’) can be found in <em>all </em>of our given paths. Both ‘/submit’ and ‘/favorites’ contain the ‘/’ character. Therefore, once Switch sees that this path is a part of our URL, it stops looking for other components to display. Because of this, we put our Home component <em>last</em>, that way the ‘/’ path is only displayed if neither ‘/submit’ nor ‘/favorites’ is in the URL. We can also fix this problem by using the attribute <strong>exact </strong>:</p><pre>&lt;Route <strong>exact </strong>path=&#39;/&#39;&gt;</pre><pre>    &lt;Home /&gt;</pre><pre>&lt;/Route&gt;</pre><p>The <strong>exact </strong>attribute makes it so that the component will only be shown if that <em>exact </em>path is in the URL, not just if <em>any part </em>of the path matches<em> </em>the URL.</p><h4>NavLink</h4><p>Now, all we need is a way for our users to access our other components without having to manually type the URL into the browser. This is where NavLink comes in! Using my anime app as an example, let’s take a look at NavLink and its functions in action:</p><pre><strong>import { NavLink } from &#39;react-router-dom&#39;; </strong>//imports NavLink</pre><pre>. . .</pre><pre>&lt;nav&gt;</pre><pre><strong>    &lt;NavLink  to=&#39;/&#39;exact&gt;</strong></pre><pre>        &lt;li&gt;&lt;a&gt;Home&lt;/a&gt;&lt;/li&gt;</pre><pre><strong>    &lt;/NavLink&gt;</strong></pre><pre><strong>    &lt;NavLink to=&#39;/favorites&#39;&gt;</strong></pre><pre>        &lt;li&gt;&lt;a&gt;Favorites&lt;/a&gt;&lt;/li&gt;</pre><pre><strong>    &lt;/NavLink&gt;</strong></pre><pre><strong>    &lt;NavLink to=&#39;/submit&#39;exact&gt;</strong></pre><pre>        &lt;li&gt;&lt;a&gt;Submit&lt;/a&gt;&lt;/li&gt;</pre><pre><strong>    &lt;/NavLink&gt;</strong></pre><pre>&lt;/nav&gt;</pre><p>Within the &lt;nav&gt; tags is the JSX being returned in the NavBar component. Taking a look at the NavLink tags, we can see each NavLink has an attribute called <em>to</em>. This attribute points to the path that we should be navigating to when a &lt;a&gt; tag on our nav bar is clicked. For example, once the ‘Favorites’ &lt;a&gt; tag is clicked, according to our &lt;NavLink&gt;, we should navigate to ‘/favorites’ in our browser. We know, from using Route and Switch earlier that this URL takes us to our Favorites component:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F2tbG6AY6FNQCWQL7NC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F2tbG6AY6FNQCWQL7NC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F2tbG6AY6FNQCWQL7NC%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="215" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed5bb5120ca8b623f202373548b4a22f/href">https://medium.com/media/ed5bb5120ca8b623f202373548b4a22f/href</a></iframe><p>Here, we can see that NavLink is an extremely useful tool to have in our React application as it allows us to dictate what pages take us to what URL.</p><p>Now we have learned how Route, Switch, and NavLink can be used to provide a way to navigate around our app using different URLs, giving even more dimension to our applications!</p><h3>Why you should use React</h3><p>React is an incredible way to create fun, dynamic, and interactive websites while being great for organization and change! If you don’t like your life to be easier, then don’t go with React. If you know what’s good for you, take the leap and learn React today! You won’t regret it!</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49e02d303436" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-create-a-dynamic-react-app-49e02d303436">How to Create a Dynamic React App</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Event Listeners]]></title>
            <link>https://medium.com/@kpinkin1/javascript-event-listeners-da4ecd62bd59?source=rss-e6ca763ab06d------2</link>
            <guid isPermaLink="false">https://medium.com/p/da4ecd62bd59</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[event-listener]]></category>
            <dc:creator><![CDATA[Kahlia Pinkins]]></dc:creator>
            <pubDate>Mon, 08 Nov 2021 09:11:03 GMT</pubDate>
            <atom:updated>2021-11-08T09:17:07.747Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever visited a website and been in awe of the number of things you could do on the page? With the click of a button, you can express your interest in a post you ‘like’. With the tap of the keyboard, you can tell Mario to jump over an angry mushroom. With a hit of the ‘Submit’ key, you can post how passionately you feel about a particular topic. These all make websites and applications extremely dynamic and can provide a much more enjoyable experience for the user. But how do we, as developers, add these wonderful experiences to our applications for the user to interact with? Why, through Event Listeners, of course!</p><h3>What is an Event Listener?</h3><p>First off, we need to figure out what exactly an event is. An <strong>event</strong> can be defined as anything that a user does on our page. This includes things such as moving the mouse, pressing a key on the keyboard, clicking something on the page, and anything else that the user may do while perusing our beautiful applications. An event <em>listener</em> does just as the name suggests: it listens, or checks, for an event that has taken place and takes action based on the developer’s instructions. When a user clicks a ‘like’ button, for instance, we may have the button turn pink to indicate that the user has liked this post!</p><h3>Syntax</h3><p>Most commonly, event listeners are added to an element of the DOM (Document Object Model). We can add an event listener by using the .addEventListener() method. This method sets up the action that is to take place once the event is triggered on the page. It takes two arguments: the event type (a string) and a callback function that will execute in response to the event, often called the <em>handler</em>. Many times we’ll see the event handler be an anonymous or arrow function. The code when adding an event listener looks like this:</p><pre>DOMElement.addEventListener(eventType, eventHandler)</pre><h3>Common Type of Events</h3><h4>The Click Event</h4><p>The click event is probably the most common and easily recognizable event in JavaScript. The click event is triggered when a user clicks on something on the page. This can be a ‘like’ button, an icon, or anything else that can be seen on our application. Let’s say we want to create a website where the user can click a button on the page and get alerted that the button has been clicked. We could use the following code:</p><pre>button.addEventListener(&#39;click&#39;, function(){<br>  alert(&#39;You clicked the button!&#39;)<br>})</pre><p>Now, every time our button is clicked, the user will see an alert that says “You clicked the button!” Notice how our callback function, or handler, here is an anonymous function. This is common when an event listener only has a few lines of code, but we should get into the habit of creating a separate event function for our longer handlers and passing that into our Event Listener function.</p><h4>The Mouseover Event</h4><p>The mouseover event is triggered when the user drags the mouse (or trackpad) over the target element. This event is often used to change the underlining or color of a link or to give the user more information about what they are hovering over. Say we want to tell our user what will happen if they click the link they have decided to hover over. We’d write the following code:</p><pre>link.addEventListener(&#39;mouseover&#39;, function(){<br>  alert(&#39;This link will take you to another page!&#39;);<br>})</pre><p>Great! Now every time our user points to that link, they’ll be alerted that the link will take them to a separate page! You’re really getting the hang of this!</p><h4>The Keydown Event</h4><p>The keydown event is another event that you’ll run into fairly often as a JavaScript programmer. This event is triggered when a button on the keyboard is pressed. An example of this would be when a user is able to press any key to continue. If we want to be more specific with which keys we allow to trigger our event, for example, Mario jumps when the spacebar is hit, we have to do a few extra steps. The first thing we need to do is identify what event code is given when pressing the spacebar. Once we know this, we will know which code to look for when adding our listener. We can see this by logging our event to the console and seeing the properties that it contains:</p><pre>window.addEventListener(&#39;keydown&#39;, event =&gt; console.log(event))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*MCfK0d6JfTuyIhmF6UJBEw.png" /><figcaption>keydown event</figcaption></figure><p>Notice that we added our event listener to the window since the keydown event is linked to the keyboard rather than anything specific on the DOM. Also notice that we passed in <em>event</em> as our function’s argument. This is because the .addEventListener() method automatically passes in the event associated with the event type we put in as its first argument. When logging it to the console, we can see the event that is taking place and all of its properties. We see here from the logged event, the event key code for pressing the spacebar is 32. We now have enough information to create a listener for our keydown event where we <em>only</em> want the spacebar to trigger an action. Let’s say we want to alert our user once we press the spacebar. We could use the code:</p><pre>window.addEventListener(&#39;keydown&#39;, function(event){<br>    if(event.keyCode === 32){<br>        alert(&#39;You pressed the spacebar!&#39;)<br>    }<br>})</pre><p>As you can see, we added an if statement to ensure that our event triggers only when the spacebar is hit (the event with the key code 32). This extra step is necessary for both key down and key up (action upon letting go of a key) events if we want to be specific with our keys.</p><h4>The Submit Event</h4><p>The submit event is very special. This is an event where a form is submitted and usually, something is rendered to the page after submission. The unique thing about the submit event is its link to HTML forms. Because the submit event is always attached to an HTML form, its default behavior is to refresh the page whenever the submit button is clicked, bypassing the rest of the code we wrote in the event handler. Because of this, we need to counteract this default action so that our form can submit without interruption. We can do this by using a method called .preventDefault(). .preventDefault() will <em>prevent </em>the default behavior of the form and the page will not refresh upon submission. Therefore, if we want to alert the user that we have submitted our form, we can use the following code:</p><pre>form.addEventListener(&#39;submit&#39;, function(event){<br>  event.preventDefault();<br>  alert(&#39;Your form has successfully been submitted!&#39;)<br>})</pre><p>Now, because we were able to prevent the page from refreshing, our submit event is successfully running!</p><h3>Why You Should Love Event Listeners</h3><p>Event Listeners are a JavaScript Developer’s best friend! Events are what connect your applications to your users. Without event listeners, our users wouldn’t be able to interact with our page in a meaningful way and would surely go and find a more interesting and interactive webpage to connect with. Get familiar with the concept of event listeners and add as many to your page as you can! I say, the more event listeners, the better! Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da4ecd62bd59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>