Learning JavaScript: 9 Common Mistakes That Are Holding You Back

A lot of people try to learn JavaScript and then give up. Then they tell themselves things like, “JavaScript is too confusing,” or worse, “Maybe I’m not cut out for web development.”

The sad part? There was no need to give up. All that was needed was a different learning approach.

In this article, we’ll cover some of the most common learning mistakes people make and find out how to avoid them. Many of these tips will be applicable outside of JavaScript or even web development, so there’s that bonus too.

Let’s dive in!

Mistake #1: Overanalyzing Instead of Getting Started

It can be tempting to look for all the information you can get before you start learning JavaScript. If you look, you’ll find information about how JavaScript is the best thing ever or the worst thing ever, or that you need to be on this framework or that framework. You might also hear that you need to write JavaScript a certain way or else you’ll never be a “real” developer.

Whether or not these points have validity, nothing is worse than the six months to a year you’ll waste agonizing instead of starting.

Just type one line of code. It doesn’t have to be perfect. It can be terrible. If you get started, you’ve already passed one of the hurdles that stop a lot of people.

Mistake #2: Learning a Framework Before Learning Plain JavaScript

JavaScript frameworks are built on top of vanilla JavaScript, so if you understand JavaScript, you automatically understand the fundamentals of how to use any JavaScript framework.

However, if you jump straight into a framework, you’ll end up memorizing without understanding. It’s like trying to write sentences without knowing what words mean. You’ll end up memorizing random phrases instead of understanding how words work and how to put them together to make your own sentences.

If you go straight to a framework it’ll be harder to learn and you’ll have a harder time adapting to another framework if you need to. If you learn plain JavaScript first, you have a firm basis to understand all the frameworks.

Mistake #3: Moving to the Next Step Too Soon

One of the most common mistakes is to move on immediately after understanding a concept.

I’ve definitely struggled with this one because it’s tempting to move forwards once you understand something.

What helped was to treat each concept like a new toy; That means taking some time to enjoy what you just learned. Play around, experiment, see if you can do something new with it. You’ll learn a lot that way, and you’ll remember better as well.

Once you feel like you can apply a concept in your sleep, move on. It takes a little bit more time up front, but soon it makes everything go much faster.

On the other hand, if you rush, you’ll end up forgetting and having to backtrack for every little thing. That ends up taking way more time, and it can be discouraging. In fact, this is a common reason people have said they quit JavaScript.

Mistake #4: Not Breaking Concepts Into Small Enough Pieces

Learning is like a staircase: If you can take one step, you can keep taking more steps until you reach your goals. When something is tough to understand, it’s often because you’re trying to take a flying leap instead of going one step at a time. Of course, it seems impossible!

Continue reading %Learning JavaScript: 9 Common Mistakes That Are Holding You Back%


Source: Sitepoint

React Crash Course for Beginners, Part 3

So far in this React series, we’ve created a working sample app as a starting point for our ‘Movie Mojo’ gallery app, and we’ve seen how using props allows us to customize the appearance of components by passing in data rather than hard coding it.

In part three we’ll create our first custom component, and then add state to our app. This will allow us to easily manage the app data without being concerned about manually updating the DOM. Instead we’ll see how to let React handle all of the DOM rendering from now on.

A set of four movies will be displayed in our gallery on page load, and a further four will be loaded and displayed when the Load more… button is clicked.

Let’s first tackle adding the <Movie /> component that will display information about an individual movie.

Adding a Movie Component

The <Movie /> component will display information about an individual movie. Multiple <Movie /> components will be displayed together to form a movie gallery of some feel-good movies. Hence the name of our React app, ‘Movie Mojo”!

Before we add the <Movie /> component, let’s update the CSS in App.js to style individual movies in the gallery. Open up App.css and replace the styles with:

This styles the gallery to display movies in a grid formation and improve spacing around other visual elements.

Also, in /public/posters/, I’ve added 12 movie posters for convenience that you can use in your own project, if you’re following along. You can download them as part of the finished project for part 4. Simply copy across the posters folder to your own React app public folder.

You can also download your own movie posters from the original website. For this tutorial, I used cinematerial.com for all the movie posters. There is a small fee to download the posters, but there are probably many other sources for posters if you want to try elsewhere.

OK, back to our <Movie /> component. Inside the /src/components/ folder, create a new Movie.js file, open it in an editor, and add the following:

This is pretty similar to the <Header /> component except we’re referencing several props rather than just the one. Let’s use our <Movie /> component to display some movies.

In App.js add four <Movie /> components inside a <div> wrapper so we can easily apply styles to just the movie elements. Here is the full App.js code:

Note how we explicitly import the <Movie /> component, just like we did for <Header />, to make it available in the code. Each movie component implements props for title, year, description, and poster.

The result is four <Movie /> components added to our gallery.

Manually adding Movie components

It’s very tedious to add movies manually one at a time in App.js. In practice, app data would likely come from a database and be temporarily stored in a JSON object before being added to the state object in your app.

Managing React State

What is state in a React app? You can think of it as a single JavaScript object which represents all the data in your app. State can be defined on any component, but if you want to share state between components then it’s better to define it on the top-level component. State can then be passed down to child components and accessed as required.

Even though state is one main object, that object can contain multiple sub-objects related to different parts of your app. For example, in a shopping cart app, you might have a state object for the items in your order, and another object for monitoring inventory.

In our ‘Movie Mojo’ app, we have just a single sub-state object to store the movies in our gallery.

The core idea behind using state is that whenever data in your app changes, React updates the relevant parts of the DOM for you. All you have to do is manage the data, or state, in your app, and React handles all the DOM updates.

Adding Movies via State

For the sake of simplicity, we’ll forgo the database step and pretend our movie data has been retrieved from a database and stored in JSON format.

To demonstrate adding items to an initial state, as well as updating state when an event occurs (such as a button press), we’ll use two JSON objects, each containing data about four movies.

In the src folder, add a new movies.js file, open it in an editor, and add the following code to define our two JSON objects:

Before we can reference the JSON objects in our <App /> component, we need to import them. Add this to the top of App.js:

Each JSON object is now available via the variables initialMovies and additionalMovies. So far, though, we don’t have any state associated with our app. Let’s fix that now.

The top-level component in our ‘Movie Mojo’ app is <App />, so let’s add our state object here. We need state to be initialized along with the component class, which we can do via the constructor function.

When using a constructor function in a React class, you need to call super() first as the Component object we’re extending needs to be initialized before anything else. Plus, the this keyword will not be available inside the constructor until after super() has returned.

To initialize our state object, add this inside the <App /> component class:

This will create an empty state object for our React app. Using the React developer tools, we can see the state object initialized directly on the <App /> component.

Adding empty state

However, we want to initialize the state object with some movies so they display straight away on page load. To do this, we can initialize the movies state object with initialMovies instead of an empty object.

This will set the initial state for our app to the four movies stored in the initialMovies JSON object, but the movies in the gallery are still being displayed via the hard-coded <Movie /> components we added earlier.

Adding movies to our initial state

We need to output the movies in the movie state object instead, which we can do by using a loop to iterate over each movie.

Start by removing the hard-coded <Movie /> components, and replace them with:

This code requires some explanation. The movie state object contains individual movies stored as objects, but to iterate over them it would be easier to work with an array instead.

So we use Object.keys() to grab all the keys for the movie objects and store them in an array. This is then iterated over using .map(), and a <Movie /> component is outputted for each movie in the movies state object.

There are a couple of changes from the previous way we added a <Movie />, though. Firstly, we pass in all the information for an individual movie via a single meta prop. This is actually more convenient than before, where we specified a separate prop for each movie attribute.

Also, notice that we specify a key prop too. This is used internally by React to keep track of components that have been added by the loop. It’s not actually available to be used by the component, so you shouldn’t try to access it in your own code.

Without a key prop, React throws an error, so it’s important to include it. React needs to know which new movies have been added, updated, or removed so it can keep everything synchronized.

We need to do one more thing before our components can be displayed. Open up Movie.js, and for each reference to a prop, prefix it with meta, as follows:

Movies initialized via state

Loading More Movies

We’ve seen how to display movies that have been added to state as our app initializes, but what if we wanted to update our movie gallery at some point?

This is where React really shines. All we have to do is update the movies in the movie state object, and React will automatically update all parts of our app that use this object. So, if we add some movies, React will trigger the <App /> component’s render() method to update our movie gallery.

Let’s see how we can implement this.

Start by adding an HTML button inside the closing div wrapper in App.js.

When the button is clicked, a class method loadAdditionalMovies is called. Add this method to the <App /> component class:

Updating state is relatively simple as long as you follow the recommended method, which is to copy the current state object to a new object, and update that copy with new items. Then, to set the new state, we call this.setState and pass in our new state object to overwrite the previous one. As soon as the state is updated, React updates only the parts of the DOM that have been affected by the change to state.

The first line in loadAdditionalMovies() uses a spread operator to copy all properties of the this.state.movies object into the new currentMovies object.

After that, we use Object.assign to merge two objects together, resulting in the list of new movies being added to the current list.

There is just one more step we need to complete before the loadAdditionalMovies() method will work. To reference any custom component method, we first need to manually bind it to the component class.

This is a quirk of React and is just something you’ll have to remember to do. Any time a method is accessed without having been manually bound, React will complain and throw a compilation error.

Add this to the class constructor in App.js:

As long as you remember to use this workaround for every custom method that requires the use of this, you won’t run into any problems.

Now, try clicking the Load more… Button. You should see four more movies added to the gallery.

Loading more movies via updating state

This demonstrates a key strength of React. That is, letting you focus on the data in your app and leave all the mundane updating of the DOM to React. To add movies, all we had to do was to update the data in our movie state object, and React took care of everything else.

Our example app is still pretty basic, but imagine a much more complex app with many components and multiple state objects. Trying to manually update the DOM as the data in your app changes would be a huge (and error-prone) task!

Conclusion

In this tutorial, we really made some progress with our ‘Movie Mojo’ app. We used React state to help manage the list of movies in our app. Not only did we add movies to the initial state object as our app initialized, but we also updated the list of movies in our gallery when the Load more… Button was clicked.

In part four, and the last tutorial in this series, we’ll take a look at how we can manually add a movie to our gallery via a custom form. Users will be able to fill out the form and add details about a movie, which will be added to the list of movies displayed in the gallery.


Source: Nettuts Web Development

Goodbye Summer, Hello Autumn! Inspiring Wallpapers To Start September Off Right (2017 Edition)




 


 

As designers we usually turn to different sources of inspiration, and, well, sometimes the best inspiration lies right in front of us. With that in mind, we embarked on a special creativity mission nine years ago: to provide you with inspiring and unique desktop wallpapers every month. Wallpapers that are a bit more distinctive as the usual crowd and that are bound to fuel your ideas.

Desktop Wallpaper Calendars September 2017

We are very thankful to all artists and designers who have contributed and are still diligently contributing to this mission, who challenge their artistic abilities each month anew to keep the steady stream of wallpapers flowing. This post features their artwork for September 2017. All wallpapers come in two versions — with and without a calendar — and can be downloaded for free. Time to freshen up your desktop!

The post Goodbye Summer, Hello Autumn! Inspiring Wallpapers To Start September Off Right (2017 Edition) appeared first on Smashing Magazine.


Source: Smashing Magazine

How to Create CSS Conic Gradients for Pie Charts and More

More and more websites use gradients in one way or another. Some websites use them for navigation components, while others use them in elements like buttons, or with images to create some nice effects.

All browsers have had support for basic CSS linear and radial gradients for a long time now. The CSS Gradients: A Syntax Crash Course article on SitePoint gives you a quick summary of the syntax required to create linear and radial gradients, as well as how to use repeating gradients to create some basic patterns, which is great if you care about web performance and try to avoid using images whenever possible.

After linear and radial gradients, browsers are now slowly starting to support conic gradients, which were first championed by Lea Verou.

In this article, you will learn about the syntax, uses, and browser support for simple conic gradients and repeating conic gradients.

What are Conic Gradients?

Conic and radial gradients are similar in the sense that both of them start from a specified or default point as the center of the circle used to draw them. The difference between the two is that, in the case of radial gradients the color-stops are placed along the radial line, while in the case of conic gradients the color stops are placed along the circumference of the circle.

The position of color-stops for a conic gradient can be specified either in terms of percentage or in terms of degrees. A value of 0% or 0deg refers to the top of the conic gradient. The values keep increasing gradually as you move clockwise. A value of 360deg is equivalent to 0deg. Any color whose color-stop value is greater than 100% or 360deg won’t be drawn on the conic gradient but it will still affect its color distribution.

The following image shows a conic gradient that starts with a yellow color and ends with orange.

Yellow and Orange Conic Gradient

It is hard not to notice the sharp transition that separates the orange at 360deg from the yellow at 0deg. Remember that conic gradients always produce this transition whenever the starting and ending colors of the conic gradient are very different. One way to avoid it is setting the starting and ending color to the same value.

Syntax for Conic Gradients

Continue reading %How to Create CSS Conic Gradients for Pie Charts and More%


Source: Sitepoint

6 jQuery Form Wizard Plugins

A jQuery Form Wizard is a jQuery plugin that assists with the creation of forms with some sort of form flow (without refreshing your page). For example, if you had a large form for entering user data, you could use a form wizard to divide it into a series of related steps. This has the advantage of not overwhelming users with a really long form and also giving them some indication of their progress as they enter their information.

In this post we list 6 of our favorite jQuery form wizards, examine their different features and finally look at a couple of paid options, as well as how to create your own. This isn’t intended to be an exhaustive list, but if you are looking for a jQuery form wizard, then hopefully this will point you in the right direction.

This popular post was updated on 30.08.2017. Broken / abandoned plugins were removed from the list and new plugins were added to reflect features people were asking for in the comments.

1. jQuery Steps

jQuery Steps is a smart UI component which allows you to easily create wizard-like interfaces. This plugin groups content into sections for a more structured and orderly page view. It has a plethora of features, such as async content loading, state persistence (it saves your input between steps) and transition effects between sections. It can be installed via NuGet or bower and has a well-documented and feature-rich API.

jQuery Steps

Homepage | GitHub | Demo

2. jQuery Smart Wizard

Smart Wizard is a flexible and heavily customizable jQuery step wizard plugin with Bootstrap support. It is easy to implement and gives a neat and stylish interface for your forms, checkout screen, registration steps etc. Its features include theme support (with various themes included), URL navigation and step selection and the ability to dynamically hide or disable steps. It can be installed via npm, bower or composer and has a well-documented and feature-rich API.

jQuery Smart Wizard

Homepage | GitHub | Demo

3. formToWizard

This lightweight plugin turns any webform into multi-step wizard with jQuery, whereby every form <fieldset> is turned into a separate step with forward and back buttons. It doesn’t have nearly as many features as the previous two plugins, but does integrate with the jQuery validation plugin to provide validation functionality. It is a single file (so you can just grab it off GitHub and go) and if JavaScript is unavailable, it degrades gracefully.

formToWizard

GitHub | Demo

Continue reading %6 jQuery Form Wizard Plugins%


Source: Sitepoint

Debunking 3 Common WordPress Myths

As the largest and most widely used content management system (CMS) on the internet, it should come as no surprise that people are constantly trying to bring WordPress down. Naturally, a number of WordPress myths have been conjured up over the years. In order to be properly informed, you have to make sure you know how to separate fact from fiction.

WordPress: The Leading CMS Platform on the Web

WordPress isn’t the only CMS around, but it certainly blows the competition out of the water in terms of adoption and appeal. Just consider the popularity of the platform:

  • As of last count, WordPress powers more than 26 percent of the web and has a whopping 59.4 percent market share, which makes it the most used CMS platform.
  • More than 500 sites a day are created on the WordPress platform.
  • There are 44,225 WordPress plugins, which have been downloaded more than 1.25 billion times.
  • WordPress is translated into 56 different languages worldwide.

These are just a few of the striking data points. When you dig into the nitty gritty of WordPress, it becomes clear that this is one of the most superior CMS platforms on the web. But along with this title comes a target. When you’re the best, people want to tear you down. And when they can’t tear you down, they resort to bending the truth or making things up altogether.

Don’t Fall for These 3 WordPress Myths

In order to be an informed website developer, entrepreneur, or business owner, you need to be cognizant of the fact that the internet is filled with myths regarding WordPress.

Here are three of the most common myths about WordPress:

Myth #1: WordPress Isn’t Scalable

Somewhere along the line, a myth has been perpetuated that WordPress isn’t scalable. Some people believe that it’s a platform that’s only suited for small blogs and tiny business websites. However, this simply isn’t true. If you look at the facts, you’ll see that WordPress is anything but a CMS designed exclusively for small sites. Just ask celebrities and businesses who regularly rely on WordPress for their websites.

Musicians like Beyonce, Justin Bieber, Snoop Dogg, Katy Perry, and The Rolling Stones all use WordPress. From the business side of things, companies like Bacardi, Sony Music, Mercedes Benz, The Rotary Club, and the New Yorker Magazine are all WordPress users.

One of the primary reasons why large businesses and brands use WordPress is that it is scalable. Not only are the search, caching, and content delivery capabilities top-notch, but there’s also true horizontal scalability. This allows websites with high traffic demands to always have sufficient architecture on-demand if they need it.

Put simply, the idea that WordPress isn’t scalable is ridiculous. “With the right infrastructure, services and resources, WordPress is highly scalable,” Pragmatic explains. “It can serve tens of thousands of logged in users at a time and deliver hundreds of millions of monthly page views. It can process page requests immediately and can produce lightning-quick results to search queries. It is flexible, upgradeable and ultimately can power all manner of websites, right up to the largest and most visited.”

Continue reading %Debunking 3 Common WordPress Myths%


Source: Sitepoint

UX Lessons from Amazon: 4 Hacks Guaranteed to Boost Conversions

I’ll admit, Amazon’s visual design is awful and kind of outdated. I’m sure many designers and UX experts will agree with me on that, so naturally, an article stating UX lessons from Amazon might raise some eyebrows at first. Bare with me though.

While Amazon still has much work to do in terms of visual design (it’s 2017 after all, users care about aesthetics!), we can still learn a lot from Amazon in regards to UX. In fact, Amazon has an amazingly-effective UX system, where research shows that they were responsible for 53% of all online retail sales growth in the U.S. in 2016.

Yes, read that again. One single company was responsible for 53% of retail sales growth in a country as big and diverse as the U.S. How did Amazon do it? Let’s take a look.

1. Having a Well-Oiled Recommendation Engine

If there’s anything that Amazon has mastered, it’s the subtle art of reading their users’ mind (or putting things into their users’ mind?). If you shop on Amazon, as soon as you order something, before you even realize that you need something to complement it, complementary options are staring you right in the face. Here’s an example:

Below is an item I’m taking a look at on Amazon—a refurbished Apple iPhone 5S:

Apple iPhone 5S on Amazon

Slightly scrolling down below reveals the following:

Amazon's recommendation engine

As you can see, Amazon has recommended a number of things I might need alongside my new iPhone: an iPhone case, a screen protector, and a T-Mobile starter kit. Not only are the recommendations timely, but they’re also essential, useful and relevant.

Now, as simple as this looks (bearing in mind that simplicity is usually the foundation of terrific UX), it’s worth paying special attention to, and here’s why. This system of recommendations, in which Amazon recommends highly-relevant products to people who are about to purchase something on its website, is so effective that it’s responsible for over 35% of their overall sales. In case that doesn’t sound impressive enough, it’s worth noting that Amazon’s Q2 revenue for 2017 was $37.96 billion dollars.

So, the first UX lesson from Amazon is to have a clear understanding of your users—their habits and reasons for using your site—and tailor your offering to them accordingly. This can boost revenue by up to a whopping 205%, according to some sources.

2. Employing a Unique Approach to Email Marketing

Amazon’s approach to email is very unique. No spam, no daily emails (like a lot of other e-commerce sites), but they drive most of their revenue via email. In fact, research shows that email plays a core role in the recommendation engine mentioned above, where it converts a lot more than Amazon’s on-site recommendations (which already converts at an impressive 60%!).

So what are Amazon getting right when it comes to email UX?

  • Personalization: Dale Carnegie famously said that the sound of our own names is the sweetest sound to us, and it seems Amazon knows this. As a result, one of the notable things in their emails to users is that users are addressed by their name.
  • Relevant and targeted emails: the difference between useful email and spam is often whether the user wanted it or not. Sometimes Amazon rarely emails. Sometimes, they email very frequently—almost every day. When Amazon sends a lot of emails, you can count on two things: one, it’s heavily targeted and tailored towards the interests of the user; and two, it’s intelligently timed around the time when the user engaged in browsing on the site. In other words, Amazon doesn’t email users “just because”. Instead, they send super-targeted emails when they know you’re looking for something (all the while also knowing exactly what you’re looking for). Really smart.
  • It’s an extension of their site: there’s no confusion about where the emails are coming from. It’s clear that it’s Amazon, because of the email experience—the look and feel, the organization of items, literally everything in the email almost feels as if you’re browsing the site. It’s a seamless experience that users are familiar with.
  • Following the KISS principle: Amazon is especially good at KISS (Keep It Simple, Stupid), one of the most proven UX principles where reducing friction and barriers to users’ taking action can result in a better conversion rate. In emails, Amazon makes it very easy to get to the next step, whether this is to learn more about a product, add it to the cart or wish list, or review something you just ordered.

Here’s an example of an email they recently sent me asking me to rate a product I ordered. Clicking on a star in the email automatically takes me to the rating page with my star rating preloaded. Amazingly simple, and considerate of my time!

Amazon's rating system

3. Removing Roadblocks to the Desired Action

Removing roadblocks is something that Amazon does well on their website too. A careful look at Amazon’s website reveals something: an intentional design in which roadblocks to the desired action have been intentionally eliminated, saving the user time, reducing their frustration and boosting conversions.

Continue reading %UX Lessons from Amazon: 4 Hacks Guaranteed to Boost Conversions%


Source: Sitepoint

React Crash Course for Beginners, Part 2

In part one of this tutorial series, we used the create-react-app tool to create a working sample app as a starting point for our ‘Movie Mojo’ gallery app.

In part two, we’ll get to grips with adding our first custom component to display individual movie cards. We’ll also see how using props allows us to customize the appearance of components by passing in data rather than hard coding it.

This demonstrates the flexibility and reusability of components, and how they can be used as powerful building blocks in your React apps.

Our First Component

OK, let’s create a component! To start with, we’ll keep things fairly simple and refactor the header HTML into its own component.

Modern React best practices recommend separating out each component in your app into a separate file. We’ll be following this principle so, in your projects /src/components/ folder, create a new file called Header.js and open it in a text editor.

At the top of component files we always start by importing required libraries, other components (as we can nest components), and extra assets we need (e.g. styles). The import statement is part of ES6 and allows us to keep our projects highly modular.

For our <Header /> component, we only need to import the React library, which we can do with this statement:

This imports the entire React library and makes it available via the React variable. It also imports the Component object directly so we can use it without having to specifically qualify it with a preceding React. object reference.

In other words, if we didn’t explicitly import the Component object then we’d have to access it as follows:

React.Component

But because we imported Component directly, we can just use it on its own without any reference to the React variable. It doesn’t matter which one you use, and is just down to preference.

Next, to actually create the component, we extend the Component object to create a new class that defines our <Header /> component. After the import statement, type:

Here, we use an ES6 class as our component container. Classes are a great way to encapsulate all the code needed to describe your component.

You might have also noticed that the component file ends with an export statement. This, as you might expect, exports our component and makes it available to other files in our project.

At the very minimum, all React components are required to have a render method, which returns some markup. This could be HTML, other React components, or a mixture of both.

Add this inside your component class:

The React.createElement() method creates an HTML element (a <div> in this case) and adds some content to it. Save changes to Header.js and open up App.js.

To use a React component inside another component, we first need to import it, so add this to the list of import statements at the top of App.js:

Note how you don’t need to add the .js file extension as this is assumed. Also, because the <Header /> component is in the same folder as our <App /> component, we don’t need to specify the full path.

In fact, if you try to use import Header from './components/Header'; from inside App.js, you’ll get a compilation error.

Component file not found

We can now add the <Header /> component inside the return statement just like any HTML element. However, there is a caveat. You can only return one top-level element inside a components return method.

So this is not allowed:

If you want to return multiple elements then you have to wrap them all up inside a single wrapper element:

So make sure that you add the <Header /> component inside the <div className="App"> element to avoid errors.

This will result in our <Header /> component being rendered.

Initial Header component

To complete the <Header /> component, we’ll remove the following block of HTML from App.js and add it to Header.js.

However, you might have noticed there is an issue. In App.js the <App /> component render method returns what looks like HTML. Yet in Header.js there’s just a single call to React.createElement(). What’s going on?

The answer is JSX. In App.js we use JSX to write HTML-like syntax to define our component output. Compare this with our component definition for Header.js.

This is how we have to write React components without JSX. In fact, under the hood, this is what JSX is compiled into before it can be rendered to the browser.

You’re not required to use JSX at all for your React components; it is entirely up to you. But almost all components you’ll come across will be written in JSX because it’s just so much easier to write.

It’s also highly readable for others new to your code. Imagine having to study a React project containing dozens of different components written in plain JavaScript!

So it should come as no surprise that we’ll be using JSX for component definitions throughout the remainder of this tutorial series.

Go ahead and replace the React.createElement() call with the JSX equivalent we copied from App.js. Your Header.js file should now look like this:

While JSX allows us much more flexibility in writing our components, bear in mind that it isn’t actual HTML we’re writing but an abstraction of it.

You can see this in the code snippet above. Notice in the <div> tag we used className rather than class to indicate where we want to declare a CSS class? This is because all JSX is compiled down to pure JavaScript, and class is a reserved word in ES6 JavaScript.

Let’s also tweak the header styles. Open App.css and edit the .App-header CSS class to be:

This updates the background color of the header and reduces the height.

Updated app styles

Component Props

So far, our <Header /> component is static. That is, it displays fixed content that never changes. But components can be made to be dynamic and display content passed into them, via component props. This makes components suddenly much more useful as they become generic and reusable.

Think of component props as similar to HTML tags. For example, a <div> tag may have attributes for id, class, style and so on that enable us to assign unique values for that specific <div> element.

We can do the same for React components. Say we didn’t want our header to output the fixed text ‘Discover Your Movie Mojo!’ all the time. Wouldn’t it be better if our header could display any text?

Unlike HTML attributes, we can name our component props whatever we like. Inside App.js, update the <Header /> tag to be:

Then, update the <Header /> component to use the text prop.

This results in our header displaying whatever text is added to the text prop in App.js.

Using props to customize the Header component

Let’s take a closer look at how we referenced the text prop inside Header.js using:

The curly braces simply tell JSX that we have some JavaScript we want to evaluate. This distinguishes it from text. If we didn’t use any curly braces, the string literal this.props.text would be outputted, which isn’t what we want.

The this keyword refers to the Header component class, and props is an object that contains all the values passed in from <Header text="David's Movie Mojo App!" />. In our case, the props object contains just the one entry, but you can add as many as you like in practice.

Our <Header /> component is now much more generic and doesn’t contain a hard-coded string. This is a good practice when writing React components. The more generic you make them, the more reusable they are.

This is good news when developing future React apps as you can reuse components from previous projects so you don’t have to write everything from scratch.

We used props above to pass a fixed string into the <Header /> component, but props can also pass variables, function references, and state to components.

To send a variable via props, we could do something like this, where headerText is a variable:

Inspecting React Components

There’s a very useful tool available for the Chrome browser that lets you inspect information about your React app.

React developer tools

The default developer tools only allow you to view normal HTML elements, but with the React Developer Tools extension installed, you can navigate through all the React components in your app.

Once it’s installed, open your browser inspector tools, and click on the newly available React tab. Notice that instead of HTML elements, you see the hierarchy of React components in your app. Click on the <App /> component to select it.

Inspecting props

Once selected, information about a component is displayed in the window to the right. The <App /> component doesn’t have any props and so the window is empty. But if you select the <Header /> component inside <App /> then you’ll see the ‘text’ prop we passed in.

Inspecting Header component props

The React developer tools are very useful for debugging, especially when you get onto developing more complex React apps, so it’s well worth getting used to using them on simpler apps.

You can also use the React developer tools to inspect your application state, which we’ll get into in the next tutorial.

Conclusion

In this tutorial you learned how to split your app into separate components to make it more modular. Component props enable you to pass in values to individual components, similar to how you add attributes to HTML elements.

We also saw how to leverage new browser inspector tools to examine components and props data.

In part 3, we’ll add state to our app to help us manage our data more effectively.


Source: Nettuts Web Development

React Crash Course for Beginners, Part 1

In this tutorial series we’ll dive right into using React as we build a fully working app to display a gallery of movies.

Learning how to build an app from scratch is a great opportunity to practise using all the key features of React whilst levelling up your development skills. All the recommended methods and best practices are followed, which is essential for creating modern React apps.

We’ll be setting up a brand new React app using the create-react-app tool, developed by Facebook, as well as covering the following React topics in detail:

  • Components 
  • JSX
  • Props
  • State
  • Structuring your app correctly
  • Using ES6 features for modern app development

What We’ll Be Building

To make learning about React development more fun, we’ll be building a fully working app, rather than presenting generic snippets of code when new aspects of React are covered.

Together we’ll build ‘Movie Mojo’, an app to display a gallery of feel-good movies. When complete, the app will load some movies on page load, and will then load in more when a button is clicked. Finally, you’ll be able to enter your own movie titles via a custom form that, when submitted, will dynamically insert a new movie into the gallery.

Finished Movie Mojo App

Prerequisites

This is an intermediate level tutorial, and so you’ll benefit greatly if you have some prior knowledge of the following topics:

  • ES6 features such as arrow functions, classes, and modules.
  • Know what React components, props, and state are.
  • Some experience using Node.js and NPM.
  • At least a basic level of JavaScript proficiency.

Most of these are covered in detail as we go along, but I’d recommend brushing up on any particular areas as necessary.

Let’s Get Set Up

We’ll be using the create-react-app tool to set up our React app. It’s extremely easy to use and will allow us to focus on coding our app straight away, without having to navigate through a complicated setup process.

To use create-react-app, you’ll need to have Node.js and npm installed. You can check if they’re both available by typing the following in a command-line window:

And then:

If they’re both installed then you’ll see the current version number for each.

If you need to install or update Node.js and npm then the simplest way is to download Node.js from the official web page. Node.js is bundled with npm so you don’t need to perform a separate installation.

To install create-react-app globally, type this into any command-line window:

npm install -g create-react-app

We can now go ahead and use create-react-app to scaffold out our new React app. It will also create a top-level folder to contain our project files. Open a command-line window and navigate to the folder you want your app located (e.g. /Desktop), and type in the following:

create-react-app movie-mojo

It will take a minute or so to complete, but when it does, you should see a message similar to this:

A new movie-mojo folder will have been created with the following file structure:

Project file structure

The src folder is where you’ll edit your project files, and when you come to deploy your app they’ll be bundled and added to the public folder, ready for distribution.

To view the sample app in your browser, let’s take advantage of the mini web server included with create-react-app. We need to be inside the project folder we just created, so in the command-line window, type:

cd movie-mojo

And then:

npm start

This simple command does three main things. It will:

  • Compile our sample React app.
  • Open a new browser window and display our app.
  • Monitor changes to project files.

Once compiled, you’ll see the following output:

And here’s the sample app running in the browser.

Sample app

When any changes are made to your app, it will automatically be recompiled and reloaded in the browser window. This is a really cool feature of create-react-app and will save you a lot of time during development!

It also allows you to focus on coding your app without being distracted by having to manually recompile and continuously refresh the browser window to see the latest changes.

Perhaps the best workflow, if you have the available screen space, is to have the browser and text editor open side by side. That way, whenever you make a change to one of your project files, you’ll see the changes almost instantly displayed in the browser window.

Let’s try out making a change to our sample project.

Inside the src folder, open App.js in your text editor. Try changing the line:

To get started, edit <code>src/App.js</code> and save to reload.

to:

Welcome to the 'Movie Mojo' React app!

As soon as you save the changes, the React app automatically recompiles, and the browser window refreshes. If you’ve rearranged your workspace as suggested above then you’ll see just how instantaneous this is.

Updated sample app

Structuring Our App

Let’s set up the structure of our app that we’ll use for the remainder of this tutorial.

The create-react-app tool does a great job of scaffolding our app, but we still have the flexibility to tweak it to suit our needs.

Firstly, let’s get rid of the files we no longer need from our src folder. We don’t need service workers in our app, so delete the registerServiceWorker.js file. This is referenced in index.js, so open it up in an editor and delete all references so it looks like this:

Next, delete the logo.svg file and edit App.js to remove references to it. Your updated file should now look like this:

We can also get rid of the App.test.js file. This will leave us with the following files in src:

  • index.js
  • index.css
  • App.js
  • App.css

We’ll be creating multiple components, so let’s create a dedicated folder to store them all in. Inside src, create a new components folder and add the App.js file to it. Our app won’t compile properly until we update a couple of references.

In index.js, update the path to import the <App /> component:

And in App.js, update the path to App.css:

Save your changes and make sure your app recompiles successfully.

We’re now almost ready to begin coding our ‘Movie Mojo’ app. First, though, let’s get familiar with how our app is rendered.

Take a look at index.js. This is the file that actually renders our app to the DOM. It does this via the ReactDom.render() method, which takes in two arguments. The first argument is the component we want to render. In our case, this is the <App /> component, which is the top-level (and currently only) component in our app.

The second argument specifies the DOM target element we want to mount our React app to. By default, ‘create-react-app’ creates this element automatically. If you take a look inside the public folder, there’s an index.html which contains a <div> element with an id of root.

You can change this to be anything you prefer, but it’s fine to leave it at the default for this tutorial.

index.js loads in our <App /> component from App.js, and we’ll be following along with this design pattern by separating out each component contained in our app into its own file.

App.js will be our top-level component which will contain other components, which in turn could contain references to other components. Think of components as being similar to HTML tags where you have the top-level <body> element which may contain one or more <div> elements, which could turn contain a <nav> menu element, and so on.

Conclusion

This tutorial contained all the groundwork required to set up our React app. Using create-react-app made it incredibly easy to build a working sample app with all the configuration handled for us. We then tweaked the default setup to suit our particular needs.

Stay tuned for part 2, where we’ll begin creating components for our ‘Movie Mojo’ app and take a look at adding props to make our components dynamic!


Source: Nettuts Web Development

An Introduction To Gravit Designer: Designing A Weather App (Part 2)




 


 

Welcome back to the second part of this tutorial on Gravit Designer. In the first part we took a general look at Gravit and set everything up, created the background image in the weather app and the status bar, and then started to make the initial elements of the design’s content. Let’s continue where we left off.

An Introduction To Gravit Designer: Designing A Weather App (Part 2)

Having created the main text layers of the content area in part one of this tutorial, let’s continue with the weather conditions for the different times of day.

The post An Introduction To Gravit Designer: Designing A Weather App (Part 2) appeared first on Smashing Magazine.


Source: Smashing Magazine