Your First PHP Code

The following is a short extract from our new book, PHP & MySQL: Novice to Ninja, 6th Edition, written by Tom Butler and Kevin Yank. It’s the ultimate beginner’s guide to PHP. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.

Now that you have your virtual server up and running, it’s time to write your first PHP script. PHP is a server-side language. This concept may be a little difficult to grasp, especially if you’ve only ever designed websites using client-side languages like HTML, CSS, and JavaScript.

A server-side language is similar to JavaScript in that it allows you to embed little programs (scripts) into the HTML code of a web page. When executed, these programs give you greater control over what appears in the browser window than HTML alone can provide. The key difference between JavaScript and PHP is the stage of loading the web page at which these embedded programs are executed.

Client-side languages like JavaScript are read and executed by the web browser after downloading the web page (embedded programs and all) from the web server. In contrast, server-side languages like PHP are run by the web server, before sending the web page to the browser. Whereas client-side languages give you control over how a page behaves once it’s displayed by the browser, server-side languages let you generate customized pages on the fly before they’re even sent to the browser.

Once the web server has executed the PHP code embedded in a web page, the result takes the place of the PHP code in the page. All the browser sees is standard HTML code when it receives the page, hence the name “server-side language.” Let’s look at simple example of some PHP that generates a random number between 1 and 10 and then displays it on the screen:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Random Number</title>
    </head>
    <body>
        <p>Generating a random number between 1 and 10:
            <?php

            echo rand(1, 10);

            ?>
        </p>
    </body>
</html>
                  

Most of this is plain HTML. Only the line between <?php and ?> is PHP code. <?php marks the start of an embedded PHP script and ?> marks its end. The web server is asked to interpret everything between these two delimiters and convert it to regular HTML code before it sends the web page to the requesting browser. If you right-click inside your browser and choose View Source (the text may be different depending on the browser you’re using) you can see that the browser is presented with the following:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Random Number</title>
    </head>
    <body>
        <p>Generating a random number between 1 and 10:
            5
        </p>
    </body>
</html>
            

Notice that all signs of the PHP code have disappeared. In its place the output of the script has appeared, and it looks just like standard HTML. This example demonstrates several advantages of server-side scripting …

  • No browser compatibility issues. PHP scripts are interpreted by the web server alone, so there’s no need to worry about whether the language features you’re using are supported by the visitor’s browser.
  • Access to server-side resources. In the example above, we placed a random number generated by the web server into the web page. If we had inserted the number using JavaScript, the number would be generated in the browser and someone could potentially amend the code to insert a specific number. Granted, there are more impressive examples of the exploitation of server-side resources, such as inserting content pulled out of a MySQL database.
  • Reduced load on the client. JavaScript can delay the display of a web page significantly (especially on mobile devices!) as the browser must run the script before it can display the web page. With server-side code, this burden is passed to the web server, which you can make as beefy as your application requires (and your wallet can afford).
  • Choice. When writing code that’s run in the browser, the browser has to understand how to run the code given to it. All modern browsers understand HTML, CSS and JavaScript. To write some code that’s run in the browser, you must use one of these languages. By running code on the server that generates HTML, you have a choice of many languages—one of which is PHP.

Basic Syntax and Statements

PHP syntax will be very familiar to anyone with an understanding of JavaScript, C, C++, C#, Objective-C, Java, Perl, or any other C-derived language. But if these languages are unfamiliar to you, or if you’re new to programming in general, there’s no need to worry about it.

Continue reading %Your First PHP Code%


Source: Sitepoint

Designing Form Layout: Color

The following is a short extract from our book, Designing UX: Forms, written by Jessica Enders. It’s the ultimate guide to form design, a key part of effective UX design. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.

Currently, our form doesn’t have much color at all:

At this stage, the only color on the form is the logo and the red asterisks indicating questions that require an answer

At this stage, the only color on the form is the logo and the red asterisks indicating questions that require an answer.

In terms of this part of the design, we’re on the right track. I’ll explain why.

Often, using color in an attempt to make a form “fun” or “interesting” can actually make the user experience worse:

This very colorful form is more scary and confusing than fun

This very colorful form is more scary and confusing than fun.

Some colors can even hurt people:

The fluorescent colors in this form may be hard for some people to look at

The fluorescent colors in this form may be hard for some people to look at.

Be Very Careful with Color

Human beings are incredibly sensitive to color. Our brains process it without us even realizing, and we can’t help noticing differences.

In our forms, we can use this feature of human biology to our advantage. Reserve color for things that need it, so they stand out in some way.

Here are some parts of a form that may benefit from color:

Buttons:

The only color on this form is the background of the button

Key messages, like errors:

Error highlighted in red

Links:

The links Terms of Use and Privacy Policy are blue

Progress indicators:

Color helps differentiate past, current and future steps

Headings:

Color used to make headings stand out

Form backgrounds:

This form has a light blue background

Branding, like logos and standard headers, may also use color:

The red header is standard branding for Coles

You may have noticed that I didn’t include the red asterisk of required field indicators (*) in the list of things that may use color. This is because I don’t recommend the use of red asterisks to indicate required fields. See “Required Versus Optional Fields” below for more information.

Notice also how each of the examples above uses very little color overall. The more color you use, the less it succeeds in making things stand out:

This form uses color on almost every element, meaning none of them stand out” width=”1446″ height=”716″ class=”aligncenter size-full wp-image-161085″ />

This form uses color on almost every element, meaning none of them stand out.

What Colors Should You Use?

Usually, your organization will have a palette of colors that you can refer to. Like my form design business, Enders Bank has a teal green as its main color, as you can see in the logo in the image below. Let’s use that color to make the primary action button on our form distinctive:

Our form now has all the color it needs

Our form now has all the color it needs.

Color Blindness

Estimates vary, but it’s likely that 4–10% of your web form’s users will have some deficiency in their ability to perceive color (typically—but inaccurately—called color blindness). The most common form of color blindness is red–green, where distinguishing between these two colors is difficult.

Continue reading %Designing Form Layout: Color%


Source: Sitepoint

Stateful vs. Stateless Functional Components in React

React is a popular JavaScript front-end library for building interactive user interfaces. React has a comparatively shallow learning curve, which is one of the reasons why it’s getting all the attention lately. 

Although there many important concepts to be covered, components are undeniably the heart and soul of React. Having a good understanding of components should make your life easy as a React developer. 

Prerequisites

This tutorial is intended for beginners who have started learning React and need a better overview of components. We will start with component basics and then move on to more challenging concepts such as component patterns and when to use those patterns. Different component classifications have been covered such as class vs. functional components, stateful vs. stateless components, and container vs. presentational components. 

Before getting started, I want to introduce you to the code snippet that we will be using in this tutorial. It is a simple counter built with React. I will be referring back to some parts of this example throughout the tutorial. 

So let’s get started. 

What Are Components?

Components are self-sustaining, independent micro-entities that describe a part of your UI. An application’s UI can be split up into smaller components where each component has its own code, structure, and API. 

Facebook, for instance, has thousands of pieces of functionality interfaced together when you view their web application. Here is an interesting fact: Facebook comprises 30,000 components, and the number is growing. The component architecture allows you to think of each piece in isolation. Each component can update everything in its scope without being concerned about how it affects other components. 

If we take Facebook’s UI as an example, the search bar would be a good candidate for a component. Facebook’s Newsfeed would make another component (or a component that hosts many sub-components). All the methods and AJAX calls concerned with the search bar would be within that component.

Components are also reusable. If you need the same component in multiple places, that’s easy. With the help of JSX syntax, you can declare your components wherever you want them to appear, and that’s it. 

Props and State

Components need data to work with. There are two different ways that you can combine components and data: either as props or state. props and state determine what a component renders and how it behaves. Let’s start with props.

props

If components were plain JavaScript functions, then props would be the function input. Going by that analogy, a component accepts an input (what we call props), processes it, and then renders some JSX code.

Stateful vs Stateless Component Component with props

Although the data in props is accessible to a component, React philosophy is that props should be immutable and top-down. What this means is that a parent component can pass on whatever data it wants to its children as props, but the child component cannot modify its props. So, if you try to edit the props as I did below, you will get the “Cannot assign to read-only” TypeError.

State

State, on the other hand, is an object that is owned by the component where it is declared. Its scope is limited to the current component. A component can initialize its state and update it whenever necessary. The state of the parent component usually ends up being props of the child component. When the state is passed out of the current scope, we refer to it as a prop.

Stateful vs Stateless Component Component with State

Now that we know the component basics, let’s have a look at the basic classification of components.

Class Components vs. Functional Components

A React component can be of two types: either a class component or a functional component. The difference between the two is evident from their names. 

Functional Components

Functional components are just JavaScript functions. They take in an optional input which, as I’ve mentioned earlier, is what we call props.

Stateful vs Stateless Components Functional Components

Some developers prefer to use the new ES6 arrow functions for defining components. Arrow functions are more compact and offer a concise syntax for writing function expressions. By using an arrow function, we can skip the use of two keywords, function and return, and a pair of curly brackets. With the new syntax, you can define a component in a single line like this. 

Class Components

Class components offer more features, and with more features comes more baggage. The primary reason to choose class components over functional components is that they can have state.

The state = {count: 1} syntax is part of the public class fields feature. More on this below. 

There are two ways that you can create a class component. The traditional way is to use React.createClass(). ES6 introduced a syntax sugar that allows you to write classes that extend React.Component. However, both the methods are meant to do the same thing. 

Class components can exist without state too. Here is an example of a class component that accepts an input props and renders JSX.

We define a constructor method that accepts props as input. Inside the constructor, we call super() to pass down whatever is being inherited from the parent class. Here are a few details that you might have missed.

First, the constructor is optional while defining a component. In the above case, the component doesn’t have a state, and the constructor doesn’t appear to do anything useful. this.props used inside the render() will work regardless of whether the constructor is defined or not. However, here’s something from the official docs:

Class components should always call the base constructor with props.

As a best practice, I will recommend using the constructor for all class components.

Secondly, if you’re using a constructor, you need to call super(). This is not optional, and you will get the syntax error “Missing super() call in constructor” otherwise. 

And my last point is about the use of super() vs. super(props). super(props) should be used if you’re going to call this.props inside the constructor. Otherwise, using super() alone is sufficient.

Stateful Components vs. Stateless Components

This is another popular way of classifying components. And the criteria for the classification is simple: the components that have state and the components that don’t. 

Stateful Components

Stateful components are always class components. As previously mentioned, stateful components have a state that gets initialized in the constructor. 

We’ve created a state object and initialized it with a count of 0. There is an alternative syntax proposed to make this easier called class fields. It’s not a part of the ECMAScript specification yet, but If you’re using a Babel transpiler, this syntax should work out of the box.

You can avoid using the constructor altogether with this new syntax.

We can now access the state within the class methods including render(). If you’re going to use them inside render() to display the value of the current count, you need to place it inside curly brackets as follows:

The this keyword here refers to the instance of the current component. 

Initializing the state is not enough—we need to be able to update the state in order to create an interactive application. If you thought this would work, no, it won’t.

 React components are equipped with a method called setState for updating the state. setState accepts an object that contains the new state of the count.

The setState() accepts an object as an input, and we increment the previous value of count by 1, which works as expected. However, there is a catch. When there are multiple setState calls that read a previous value of the state and write a new value into it, we might end up with a race condition. What that means is that the final results won’t match up with the expected values.

Here is an example that should make it clear for you. Try this in the codesandbox snippet above.

We want the setState to increment the count by 100, then update it by 1, and then remove that 100 that was added earlier. If setState performs the state transition in the actual order, we will get the expected behavior. However, setState is asynchronous, and multiple setState calls might be batched together for better UI experience and performance. So the above code yields a behavior which is different from what we expect.

Therefore, instead of directly passing an object, you can pass in an updater function that has the signature:

prevState is a reference to the previous state and is guaranteed to be up to date. props refers to the component’s props, and we don’t need props to update the state here, so we can ignore that. Hence, we can use it for updating state and avoid the race condition.

The setState() rerenders the component, and you have a working stateful component.

Stateless Components

You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for stateless functional components. There are a lot of benefits if you decide to use stateless functional components here; they are easy to write, understand, and test, and you can avoid the this keyword altogether. However, as of React v16, there are no performance benefits from using stateless functional components over class components. 

The downside is that you can’t have lifecycle hooks. The lifecycle method ShouldComponentUpdate() is often used to optimize performance and to manually control what gets rerendered. You can’t use that with functional components yet. Refs are also not supported.

Container Components vs. Presentational Components

This is another pattern that is very useful while writing components. The benefit of this approach is that the behavior logic is separated from the presentational logic.

Presentational Components

Presentational components are coupled with the view or how things look. These components accept props from their container counterpart and render them. Everything that has to do with describing the UI should go here. 

Presentational components are reusable and should stay decoupled from the behavioral layer. A presentational component receives the data and callbacks exclusively via props and when an event occurs, like a button being pressed, it performs a callback to the container component via props to invoke an event handling method. 

Functional components should be your first choice for writing presentational components unless a state is required. If a presentational component requires a state, it should be concerned with the UI state and not actual data. The presentational component doesn’t interact with the Redux store or make API calls. 

Container Components

Container components will deal with the behavioral part. A container component tells the presentational component what should be rendered using props. It shouldn’t contain limited DOM markups and styles. If you’re using Redux, a container component contains the code that dispatches an action to a store. Alternatively, this is the place where you should place your API calls and store the result into the component’s state. 

The usual structure is that there is a container component at the top that passes down the data to its child presentational components as props. This works for smaller projects; however, when the project gets bigger and you have a lot of intermediate components that just accept props and pass them on to child components, this will get nasty and hard to maintain. When this happens, it’s better to create a container component unique to the leaf component, and this will ease the burden on the intermediate components.

So What Is a PureComponent?

You will get to hear the term pure component very often in React circles, and then there is React.PureComponent. When you’re new to React, all this might sound a bit confusing. A component is said to be pure if it is guaranteed to return the same result given the same props and state. A functional component is a good example of a pure component because, given an input, you know what will be rendered. 

Class components can be pure too as long as their props and state are immutable. If you have a component with a ‘deep’ immutable set of props and state, React API has something called PureComponent. React.PureComponent is similar to React.Component, but it implements the ShouldComponentUpdate() method a bit differently. ShouldComponentUpdate() is invoked before something is rerendered. The default behaviour is that it returns true so that any change to the state or the props rerenders the component.

However, with PureComponent, it performs a shallow comparison of objects. Shallow comparison means that you compare the immediate contents of the objects instead of recursively comparing all the key/value pairs of the object. So only the object references are compared, and if the state/props are mutated, this might not work as intended. 

React.PureComponent is used for optimizing performance, and there is no reason why you should consider using it unless you encounter some sort of performance issue. 

Final Thoughts

Stateless functional components are more elegant and usually are a good choice for building the presentational components. Because they are just functions, you won’t have a hard time writing and understanding them, and moreover, they are dead easy to test. 

It should be noted that stateless functional components don’t have the upper hand in terms of optimization and performance because they don’t have a ShouldComponentUpdate() hook. This might change in future versions of React, where functional components might be optimized for better performance. However, if you’re not critical of the performance, you should stick to functional components for the view/presentation and stateful class components for the container.

Hopefully, this tutorial has given you a high-level overview of the component-based architecture and different component patterns in React. What are your thoughts on this? Share them through the comments.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in Envato Market that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.


Source: Nettuts Web Development

SmashingConf 2018: Fetch Those Early-Bird Tickets! 🇬🇧 🇺🇸 🇨🇦




 


 

Great conferences are all about learning new skills and making new connections. That’s why we’ve set up a couple of new adventures for SmashingConf 2018 — just practical sessions, new formats, new lightning talks, evening sessions and genuine, interesting conversations — with a dash of friendly networking! Taking place in London, San Francisco, Toronto. Tickets? Glad you asked!

A queen cat welcoming you a Smashing Conference in London, February 7 to 8, 2018
SmashingConf London: everything web performance. Feb 7–8.

Performance matters. Next year, we’re thrilled to venture to London for our brand new conference fully dedicated to everything front-end performance. Dealing with ads, third-party scripts, A/B testing, HTTP/2, debugging, JAM stack, PWA, web fonts loading, memory/CPU perf, service workers. Plus lightning community talks.

The post SmashingConf 2018: Fetch Those Early-Bird Tickets! 🇬🇧 🇺🇸 🇨🇦 appeared first on Smashing Magazine.


Source: Smashing Magazine

TypeScript for Beginners, Part 5: Generics

The second tutorial in our TypeScript for Beginners series focused on basic data types available in TypeScript. The type checking in TypeScript allows us to make sure that the variables in our code can only have specific types of values assigned to them. This way we can avoid a lot of mistakes while writing code because the IDE will be able to tell us when we are performing an operation on a type that it does not support. This makes type checking one of the best features of TypeScript.

In this tutorial, we will focus on another important feature of this language—generics. With generics, TypeScript enables you to write code that can act on a variety of data types instead of being limited to a single one. You will learn about the need for generics in detail and how it’s better than just using the any data type available in TypeScript.

The Need for Generics

If are not familiar with generics, you might be wondering why we need them at all. In this section, I will answer this question for you. Let’s begin by writing a function that will return a random element from an array of numbers.

The randomElem function we just defined takes an array of numbers as its only parameter. The return type of the function has also been specified as a number. We are using the Math.random() function to return a floating-point random number between 0 and 1. Multiplying it with the length of a given array and calling Math.floor() on the result gives us a random index. Once we have the random index, we return the element at that specific index.

Some time later, let’s say you need to get a random string element from an array of strings. At this point, you may decide to create another function which specifically targets strings.

What if you need to select a random element from an array of an interface that you defined? Creating a new function every time you want to get a random element from an array of different kinds of objects is not feasible.

One solution for this problem is to set the type of array parameter being passed to the functions as any[]. This way you can just write your function only once, and it will work with an array of all types.

As you can see, we can use the above function to get random positions as well as random colors. One major problem with this solution is that you will lose the information about the type of value that is being returned. 

Earlier, we were sure that randomPosition would be a number and randomColor would be a string. This helped us in using these values accordingly. Now, all we know is that the returned element could be of any type. In the above code, we could specify the type of randomColor to be a number and still not get any error.

A better solution to avoid code duplication while still preserving the type information is to use generics. Here is a generic function that returns random elements from an array.

Now, I will get an error if I try to change the type of randomColor from string to number. This proves that using generics is a lot safer than using the any type in such situations.

TypeScript Generics Error

Using Generics May Seem Very Limiting

The previous section discussed how you can use generics instead of the any type in order to write a single function and avoid sacrificing the benefits of type checking. One problem with the generic function that we have written in the previous section is that TypeScript won’t let us perform a lot of operations on the variables passed to it. 

This is because TypeScript can’t make any assumptions about the type of variable that will be passed to our generic function beforehand. As a result, our generic function can only use those operations which are applicable on all data types. The following example should make this concept clearer.

The above function will remove all occurrences of the specified character from the given string. You might want to create a generic version of this function so that you can also remove specific digits from a given number as well as characters from a string. Here is the corresponding generic function.

The removeChar function did not show you an error. However, if you use replace inside removeIt,TypeScript will tell you that replace doesn’t exist for type ‘T’. This is because TypeScript can no longer assume that theInput is going to be a string.

This restriction on using different methods in a generic function might lead you to think that the concept of generics is not going to be of much use after all. There is not really much that you can do with a handful of methods that must be applicable on all data types for you to use them inside a generic function.

One important thing that you should remember at this point is that you don’t generally need to create functions that will be used with all kinds of data types. It is more common to create a function that will be used with a specific set or range of data types. This constraint on data types makes generic functions much more useful.

Create Generic Functions Using Constraints

The generic removeIt function from the previous section showed an error because the replace method inside it is meant to be used with strings, while the parameters passed to it could have any data type. 

You can use the extends keyword to constrain the data types that are passed to a generic function in TypeScript. However, extends is limited to just interfaces and classes. This means that most generic functions that you create will have parameters that extend a base interface or class. 

Here is a generic function that prints the name of people, family members or celebrities passed to it.

In the above example, we have defined three interfaces, and each of them has a name property. The generic printName function that we created will accept any object that extends People. In other words, you can pass either a family or a celebrity object to this function, and it will print its name without any complaints. You can define many more interfaces, and as long as they have a name property, you will be able to use the printName function without any issue.

This was a very basic example, but you can create more useful generic functions once you are more comfortable with the whole process. For instance, you can create a generic function that calculates the total value of different items sold in a given month as long as each item has a price property to store the price and a sold property that stores the number of items sold. Using generics, you will be able to use the same function as long as the items extend the same interface or class.

Final Thoughts

In this tutorial, I have tried to cover the basics of generics in TypeScript in a beginner-friendly manner. We began the article by discussing the need for generics. After that, we learned about the right way to use generics in order to avoid code duplication without sacrificing the type checking ability. Once you understand the basics discussed here, you can read more about generics in the official documentation.

If you have any questions related to this tutorial, I will be happy to answer them in the comments.


Source: Nettuts Web Development

Inspiring Desktop Wallpapers To Make November Even More Colorful (2017 Edition)




 


 

November is a rather gray month in many parts of the world, so what could be better as some colorful inspiration to start it off with the right foot? To tickle your creativity, artists and designers from across the globe once again challenged their artistic abilities and designed desktop wallpapers for you to indulge in. Wallpapers that are a bit more distinctive as the usual crowd, bound to breathe some fresh life into your routine.

Desktop Wallpaper Calendars November 2017

All artworks in this collection come in versions with and without a calendar for November 2017, so it’s up to you to decide if you want to have the month always in sight or just some distraction-free inspiration. A big thank-you to everyone who shared their wallpapers this time around! Enjoy!

The post Inspiring Desktop Wallpapers To Make November Even More Colorful (2017 Edition) appeared first on Smashing Magazine.


Source: Smashing Magazine

Build a React App with User Authentication in 15 Minutes

This article originally appeared on the OKTA blog. Thank you for supporting the partners who make SitePoint possible.

React has quickly become one of the most favored front-end web frameworks, and is second only to plain old HTML5, according to JAXenter. So it’s no surprise that developers are learning it, and employers are asking for it.

In this tutorial, you’ll start with a very simple React app with a couple of pages and some routing built in, and add authentication using Okta’s Sign-In Widget. The Sign-In Widget is an embeddable Javascript widget that allows developers to use Okta’s secure, scalable architecture with a minimum of effort from within React applications. Let’s get started!

Get the Simple React Seed Project

Start by cloning the simple React seed project.

git clone https://github.com/leebrandt/simple-react-seed.git okta-react-widget-sample
cd okta-react-widget-sample

Add the Okta Sign-In Widget

Install the Okta Sign-In Widget using npm.

npm install @okta/okta-signin-widget@2.3.0 --save

This will add the Okta Sign-In Widget code to your node_modules folder. We’ll be using version 2.3.0 of the Sign-In Widget.

Okta in node_modules

Then add the styles for the widget in your index.html file from the Okta CDN. Add these lines inside the <head> tag:

    <link
     href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.3.0/css/okta-sign-in.min.css"
      type="text/css"
      rel="stylesheet"/>

    <!-- Theme file: Customize or replace this file if you want to override our default styles -->
    <link
      href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.3.0/css/okta-theme.css"
      type="text/css"
      rel="stylesheet"/>

The LoginPage Component

First, create a folder called auth in the ./src/components folder, then create a file called LoginPage.js where the LoginPage component will go.

Start with the most basic of components:

import React from 'react';

export default class LoginPage extends React.Component{
  render(){
    return(
      <div>Login Page</div>
    );
  }
}

This little component doesn’t do much but at least you now have a handle to add the LoginPage to your routing. So in your ./src/app.js file, you’ll import the component at the top:

import LoginPage from './components/auth/LoginPage';

and then add the route inside the main route (the one with the path of “/”)

<Route path="/login" component={LoginPage}/>

Add the OpenID Connect Application in Okta

In order to use Okta as your OpenID Connect provider for authentication, you’ll need to set up an application in the Okta developer console.

If you don’t have an Okta developer account, go create one! Once you’re logged in, click on Applications in the top navbar, then click Add Application. Select SPA as the platform and click Next. Change the redirect URI to http://localhost:3000, and click Done. The application will be created with the following settings:

OIDC Application Settings

Now that you have an application created in Okta, you can set up the widget to talk to your new app!

Add the Widget to Your Component

import React from 'react';
import OktaSignIn from '@okta/okta-signin-widget';

export default class LoginPage extends React.Component{
  constructor(){
    super();
    this.widget = new OktaSignIn({
      baseUrl: 'https://{oktaOrgUrl}',
      clientId: '{clientId}',
      redirectUri: 'http://localhost:3000',
      authParams: {
        responseType: 'id_token'
      }
    });
  }

  render(){
    return(
      <div>Login Page</div>
    );
  }
}

Copy the Client ID generated from your application’s settings page and paste it over {clientId}. Make sure you also replace {oktaOrgUrl} with your Okta organization URL, which you can find by going back to the main Dashboard page in the developer console. Usually it will look like: https://dev-12345.oktapreview.com.

Thus far you’ve imported the OktaSignIn function from the Okta Sign-In Widget npm module you installed earlier. Next, in the constructor of the component, you initialized an instance of OktaSignIn with the configuration for the application. This way, the application code will be able to talk to Okta and Okta will recognize that this is the app you just created.

Show The Login Widget

Next, you’ll create the code to actually render the Sign-In Widget to the page! You’ll need to change your render method to create an HTML element you can render the widget into. Make sure to get a reference to the element that will be rendered. Then, add a componentDidMount function to make sure you don’t try to render the widget before the HTML element is on the page.

Continue reading %Build a React App with User Authentication in 15 Minutes%


Source: Sitepoint

Designing Form Layout: Spacing

The following is a short extract from our book, Designing UX: Forms, written by Jessica Enders. It’s the ultimate guide to form design, a key part of effective UX design. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.

We can subtly communicate with the user through a few tweaks of spacing.

Proximity

Human beings see things that are close to each other as being related. Conversely, things that are not related usually have some space between them.

These principles tell us to put the parts of a question—label, question-level help and answer fields—close together. Our form is pretty good for this so far, but let’s just move the labels a bit to the right, so they’re closer to their fields:

Flush right labels should be close to their fields

Flush right labels should be close to their fields.

On the other hand, there needs to be some distance between each question:

Questions should be far enough apart that it’s clear where one ends and the next one starts

Questions should be far enough apart that it’s clear where one ends and the next one starts.

Remember how the focus of a user’s vision is about nine characters wide? Well, this means question-level help that’s on the right side of a field often won’t be seen:

Their focus on fields means many users won’t even see the question-level help in this form

Their focus on fields means many users won’t even see the question-level help in this form.

We could move the question-level help underneath the field, but that means users might not see it until after they’ve answered. It’s also less accessible.

Question-level help below the field is not especially usable or accessible

Question-level help below the field is not especially usable or accessible.

The best place for question-level help is between the label and the field (as shown in the image below). Formatting instructions—like the DD MM YYYY on date of birth—should go above the field:

Formatting instructions positioned above the field

Formatting instructions positioned above the field

Other question-level help should go below the label. See the ABN, employee and marketing questions for examples of this:

Other question-level help positioned below the label.

Other question-level help positioned below the label.

Finally, when we use checkboxes and radio buttons, we need to make sure the labels are close to the right button or box. If they’re too far away, things get confusing, particularly if you aren’t shading the touch area:

The distance between the labels “Yes” and “No” and their respective radio buttons means the user has to stop and think

The distance between the labels “Yes” and “No” and their respective radio buttons means the user has to stop and think.

Here’s an even more extreme illustration of poorly spaced labels on radio buttons:

It’s likely that many users will give an unintended rating, given the poor spacing here

It’s likely that many users will give an unintended rating, given the poor spacing here.

Text Box Widths

While we’re adjusting spacing, let’s fix up our text box widths.

At the moment, aside from the text boxes for date of birth, all our text boxes are the same width:

Text boxes all the same width

However, the width of a text box tells the user what sort of information is needed. The user experience will be better if we make the sizes proportional to the expected information (as we have, in fact, already done with date of birth):

Text boxes adjusted to have width proportional to typical answers

Note we’re talking about visual width here, not acceptable number of characters. The email address field may have a visual width as shown, but should still accept up to 256 characters.

Empty Text Boxes

Another important aspect of text box spacing is the space they have inside. This empty space is how users know they need to type something in there.

Way too many forms have text boxes that aren’t empty. The two main culprits are:

  1. background color
  2. placeholder text.

No Background Color

Do not give your fields a background color. Background color in fields makes them look like buttons (just as buttons without background color look like fields):

On this form, background color makes fields look like buttons, and vice versa

On this form, background color makes fields look like buttons, and vice versa.

A simple border on four sides is enough to show users where to type:

You don’t need much to show users where their answers go

You don’t need much to show users where their answers go.

Just make sure your border can be seen:

The field borders on this form are so light they’re nearly impossible to see

The field borders on this form are so light they’re nearly impossible to see.

Continue reading %Designing Form Layout: Spacing%


Source: Sitepoint

Designing Form Layout: Alignment

The following is a short extract from our book, Designing UX: Forms, written by Jessica Enders. It’s the ultimate guide to form design, a key part of effective UX design. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.

You and a friend are each driving to a restaurant for dinner. Both of your routes go down a highway with two lanes. The highways are the same length. On your route, all the slow cars are doing the right thing and sticking to one lane, so you can whizz past in the other. On your friend’s route, the slow cars are scattered across both lanes of the highway, so she has to weave in and out. Which one of you will get to the restaurant first?

Vertical Path to Completion

A straight, unobstructed route is fastest for driving, and also for form filling. So your next step is to vertically line up all your form fields, as well as the main button on the page (called the primary action button):

Answer fields and the primary action button are vertically aligned” width=”998″ height=”1000″ class=”aligncenter size-full wp-image-160935″ />

Now you’ve created a straight, unobstructed, vertical path to completion. Not only have you made it faster for your form to be filled out, it looks neater and simpler too. (We’ll talk about the distance between some fields and their labels shortly.)

Don’t Put Questions Beside Each Other

Because a vertical path to completion makes a form longer, you may be tempted to squeeze some questions next to each other:

In this form, the Security Code and Postal Code questions have been put beside other questions

In this form, the Security Code and Postal Code questions have been put beside other questions

This is a bad idea, for the following reasons:

  • It interrupts the smooth flow through the form (like a broken down car in your fast lane).
  • Users will often not see the question on the right-hand side, because it’s outside the focus of their vision (this is only about nine characters wide).
  • It prevents the form from working seamlessly on both large and small screens. (More on this shortly.)

Also, as you may recall from Chapter 3, for users it’s the perceived length of the form, not the actual length, that matters. The vertical path to completion makes form filling not only objectively faster, but it makes it feel fast.

Aligning Answer Fields

One way you can sometimes save space, however, is with answer fields. Look at the answer fields for the marketing consent question:

Marketing consent question, with vertical answer fields

Whenever the answer fields are small, we can put them horizontally. (For this purpose we define “small” as three or fewer options, all with short labels.) The form will still work for touch, and on small screens. Marketing consent is just such a question:

Marketing consent question, with horizontal answer fields

In fact, date of birth is also a question with small answer fields. You may not have realized we’ve already put them on one line:

The date of birth question has three small answer fields

But remember: you can only put answer fields beside each other if they’re small. Otherwise, the design won’t work in some cases. Social networking, for instance, has quite a large number of answer options. If we try to put them horizontally, they’ll go off the edge—especially on mobile—and invoke the dreaded horizontal scrollbar:

If we position a long set of answer fields horizontally, we’re likely to conjure the horizontal scrollbar, even on larger screens

If we position a long set of answer fields horizontally, we’re likely to conjure the horizontal scrollbar, even on larger screens

If our answer fields aren’t small, it’s even more likely we’ll cause the horizontal scrollbar to appear on mobile

If our answer fields aren’t small, it’s even more likely we’ll cause the horizontal scrollbar to appear on mobile.

Assuming we can’t build a custom widget, it’s better to leave these as a single vertical list:

Larger sets of radio buttons or checkboxes should be vertically aligned

Larger sets of radio buttons or checkboxes should be vertically aligned.

Vertical alignment of sets of radio buttons or checkboxes works on mobile too

Vertical alignment of sets of radio buttons or checkboxes works on mobile too.

Label Placement

There’s a problem with the mobile view of our form, which you may have noticed from some of the illustrations above. On a small screen, when the focus is in a text box, the corresponding label isn’t visible, just like this example:

Continue reading %Designing Form Layout: Alignment%


Source: Sitepoint

How to Optimize MySQL: Indexes, Slow Queries, Configuration

MySQL is still the world’s most popular relational database, and yet, it’s still the most unoptimized – many people leave it at default values, not bothering to investigate further. In this article, we’ll look at some MySQL optimization tips we’ve covered previously, and combine them with novelties that came out since.

Configuration Optimization

The first – and most skipped! – performance upgrade every user of MySQL should do is tweak the configuration. 5.7 (the current version) has much better defaults than its predecessors, but it’s still easy to make improvements on top of those.

We’ll assume you’re using a Linux-based host or a good Vagrant box like our Homestead Improved so your configuration file will be in /etc/mysql/my.cnf. It’s possible that your installation will actually load a secondary configuration file into that configuration file, so look into that – if the my.cnf file doesn’t have much content, the file /etc/mysql/mysql.conf.d/mysqld.cnf might.

Editing Configuration

You’ll need to be comfortable with using the command line. Even if you haven’t been exposed to it yet, now is as good a time as any.

If you’re editing locally on a Vagrant box, you can copy the file out into the main filesystem by copying it into the shared folder with cp /etc/mysql/my.cnf /home/vagrant/Code and editing it with a regular text editor, then copying it back into place when done. Otherwise, use a simple text editor like vim by executing sudo vim /etc/mysql/my.cnf.

Note: modify the above path to match the config file’s real location – it’s possible that it’s actually in /etc/mysql/mysql.conf.d/mysqld.cnf

Manual Tweaks

The following manual tweaks should be made out of the box. As per these tips, add this to the config file under the [mysqld] section:

innodb_buffer_pool_size = 1G # (adjust value here, 50%-70% of total RAM)
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 1 # may change to 2 or 0
innodb_flush_method = O_DIRECT
  • innodb_buffer_pool_size – the buffer pool is a storage area for caching data and indexes in memory. It’s used to keep frequently accessed data in memory, and when you’re running a dedicated or virtual server where the DB will often be the bottleneck, it makes sense to give this part of your app(s) the most RAM. Hence, we give it 50-70% of all RAM. There’s a buffer pool sizing guide available in the MySQL docs.
  • the log file size is well explained here but in a nutshell it’s how much data to store in a log before wiping it. Note that a log in this case is not an error log or something you might be used to, but instead it indicates checkpoint time because with MySQL, writes happen in the background but still affect foreground performance. Big log files mean better performance because of fewer new and smaller checkpoints being created, but longer recovery time in case of a crash (more stuff needs to be re-written to the DB).
  • innodb_flush_log_at_trx_commit is explained here and indicates what happens with the log file. With 1 we have the safest setting, because the log is flushed to disk after every transaction. With 0 or 2 it’s less ACID, but more performant. The difference in this case isn’t big enough to outweigh the stability benefits of the setting of 1.
  • innodb_flush_method – to top things off in regards to flushing, this gets set to O_DIRECT to avoid double-buffering. This should always be done, unless the I/O system is very low performance. On most hosted servers like DigitalOcean droplets you’ll have SSDs, so the I/O system will be high performance.

There’s another tool from Percona which can help us find the remaining problems automatically. Note that if we had run it without the above manual tweaks, only 1 out of 4 fixes would have been manually identified because the other 3 depend on user preference and the app’s environment.

Continue reading %How to Optimize MySQL: Indexes, Slow Queries, Configuration%


Source: Sitepoint