Foxplx
- Home
- Foxplx
Contact information, map and directions, contact form, opening hours, services, ratings, photos, videos and announcements from Foxplx, Web designer, .
01/08/2018
The Month in WordPress: July 2018 https://wordpress.org/news/2018/08/the-month-in-wordpress-july-2018/
With WordPress 5.0 coming closer, there’s lots of work going on all across the project. Read on to learn about how we progressed in July.
Release of WordPress 4.9.7
On July 5, WordPress 4.9.7 was released, fixing one security issue and 17 other bugs across the platform.
While this is a minor release, incremental fixes are essential to keep WordPress running smoothly. Everyone is encouraged to update as soon as possible and to make sure that automatic updates are switched on.
Would you like to get involved in building WordPress Core? Follow the Core team blog and join the channel in the Making WordPress Slack group.
The New WordPress Editor
In the upcoming minor release of WordPress, 4.9.8, a new section in the dashboard will feature Gutenberg, the upcoming content editor for WordPress.
While the official release of Gutenberg is scheduled for the coming months, you can already install it as a plugin to test it out right now. Additionally, a brand new demo page is now available — play around with the many features the editor has to offer, without installing it on your own site.
Would you like to help build or test Gutenberg? Follow the Core team blog and join the -editor channel in the Making WordPress Slack group.
Page Design Updates on WordPress.org
Bit by bit we’re refreshing the design of WordPress.org. The latest pages to get a new treatment have been the Download page and user profiles.
The Meta and Design teams worked hard to make these new designs a reality, with notable contributions from , , , and . The new designs enhance the overall look of the site and provide more relevant information to those searching.
Would you like to get involved in the design refresh? Follow the Meta and Design team blogs and join the and channels in the Making WordPress Slack group.
The First WP-CLI Hack Day
On Friday July 20, the WP-CLI team held their first hack day — a global event encouraging people to contribute to the official command line tool for WordPress.
Run by , the event was a great success. Twelve pull requests were merged and another 13 submitted. It also included a video chat to give all contributors a space to meet each other and connect directly.
Would you like to get involved in contributing to WP-CLI? Follow the team blog and join the channel in the Making WordPress Slack group.
Further Reading:
The WordPress Foundation is looking for local community organizers to run introductory open-source workshops in 2018.
compiled updates for the last quarter from the contribution teams all across the WordPress project.
In a great move for internationalization, the WordPress Mobile Apps now support right-to-left languages.
WordCamp events can now accept payment via Stripe — PayPal remains an alternative option.
The WP-CLI team will soon release v2.0 of the official WordPress command line tool.
The Fields API project in WordPress Core is looking for a new lead to drive it forward.
In WordPress 4.9.8, it will be possible for developers to fully register the meta fields used by their plugins and themes.
After many years of hard work, v1.0.0 of the WordPress Coding Standards for PHP_CodeSniffer has been released.
The Mobile team is looking for people to help test v10.6 of WordPress for iOS.
If you have a story we should consider including in the next “Month in WordPress” post, please submit it here.
01/08/2018
How to use Media Queries in JavaScript with matchMedia https://www.sitepoint.com/javascript-media-queries/
When it was first introduced, responsive design was one of the most exciting web layout concepts since CSS replaced tables. The underlying technology uses media queries to determine the viewing device type, width, height, orientation, resolution, aspect ratio, and color depth to serve different stylesheets.
If you thought responsive design was reserved for CSS layouts only, you'll be pleased to hear media queries can also be used in JavaScript, as this article will explain.
Media Queries in CSS
In the following example, cssbasic.css is served to all devices. But, if it's a screen with a horizontal width of 500 pixels or greater, csswide.css is also sent:
[code language="html"]
[/code]
The possibilities are endless and the technique has long been exploited by most websites out there on the Internet. Resizing the width of your browser triggers changes in the layout of the webpage.
With media queries nowadays it's easy to adapt the design or resize elements in CSS. But what if you need to change the content or functionality? For example, on smaller screens you might want to use a shorter headline, fewer JavaScript libraries, or modify the actions of a widget.
It's possible to analyze the viewport size in JavaScript but it's a little messy:
Most browsers support window.innerWidth and window.innerHeight. (IE before version 10 in quirks mode required document.body.clientWidth and document.body.clientHeight.)
window.onresize
All the main browsers support document.documentElement.clientWidth and document.documentElement.clientHeight but it's inconsistent. Either the window or document dimensions will be returned depending on the browser and mode.
Even if you successfully detect viewport dimension changes, you must calculate factors such as orientation and aspect ratios yourself. There's no guarantee it'll match your browser's assumptions when it applies media query rules in CSS.
The post How to use Media Queries in JavaScript with matchMedia appeared first on SitePoint.
31/07/2018
Amelia: The Next-level WordPress Booking Plugin https://www.sitepoint.com/amelia-the-next-level-wordpress-booking-plugin/
This article was created in partnership with BAWMedia. Thank you for supporting the partners who make SitePoint possible.
Booking appointments would seem to be a minor task, but managing appointments takes up more time, energy, and money than you might imagine, especially in very active businesses like consulting firms, health and fitness clubs, and beauty salons.
Manual booking methods often work reasonably well, but they are by no means flawless. Mistakes will be made, appointments will slip through the cracks, and appropriate parties can fail to be properly informed when changes occur.
An excellent way to avoid these pitfalls is to simplify the booking process while at the same time making it totally reliable and error-free. That way has a name. It’s Amelia, and Amelia even works while you sleep.
Introducing Amelia, the Automated Booking Specialist
Its users will tell you that it was high time for a tool like Amelia, a WordPress plugin that makes and manages appointments without fail and does so 24/7. Amelia was created with individuals and businesses like coaches and personal trainers, private clinics and health clubs, consultants, and beauty salons in mind.
Amelia requires no technical expertise whatsoever to install, it’s easy to set up, and once that’s done it’s 100% automated. Clients can make appointments at any time day or night with just a few clicks, and you can set your calendar, view those appointments and manage your business team, flawlessly and from one place.
Install Amelia, and you’ve just replaced sticky notes, scurrying, and meeting attendance goofs with a reliable appointment system that operates flawlessly on autopilot.
Amelia's Top Benefits
You’ll save more money than you’d think. You don’t pay Amelia hourly, nor is Amelia a salaried employee. You simply pay a one-time fee for what Amelia will do for you forever, and that fee is so low that your ROI is almost instantaneous. From the minute Amelia is set up and running, you’re saving money.
The post Amelia: The Next-level WordPress Booking Plugin appeared first on SitePoint.
31/07/2018
How to Apply CSS3 Transforms to Background Images https://www.sitepoint.com/css3-transform-background-image/
CSS transformations are really cool, but they don't yet apply to background images. This article presents a neat workaround for those times when you really do want to rotate a background image, or to keep a background image fixed while its container element is rotate.
This article was updated in 2018.
Interested in mastering CSS3 like a pro? CSS Master, by Tiffany Brown, is available for download to all SitePoint Premium members. Alternatively, you can grab your copy of the book for just $19.
Scaling, skewing and rotating any element is possible with the CSS3 transform property. It's supported in all modern browsers without vendor prefixes. (I've added in the -webkit- just in case you want to support some older browsers.)
[code language="css"]
{
-webkit-transform: rotate(30deg);
transform: rotate(30deg);
}
[/code]
Great stuff. However, this rotates the whole element — its content, border and background image. What if you only want to rotate the background image? Or what if you want the background to remain fixed while the element is rotated?
Currently, there's no W3C proposal for background-image transformations. It would be incredibly useful, so I suspect one will appear eventually, but that doesn't help developers who want to use similar effects today.
Fortunately, there is a solution. In essence, it's a hack which applies the background image to a before or after pseudo element rather than the parent container. The pseudo element can then be transformed independently.
The post How to Apply CSS3 Transforms to Background Images appeared first on SitePoint.
30/07/2018
5 Great HTML5 Video Players https://www.sitepoint.com/5-great-html5-video-players/
There has been an increasing demand for creators to develop their own custom video platform which they can use to advance their own advertising, marketing or branding goals. Although YouTube and other similar platforms are generally more promising, hosting videos on your own and using a video player of your choice offers more control over how your videos are used.
Irrespective of whether you are a YouTube video creator or social media influencer, we've compiled a list of 5 of the greatest HTML5 video players. This list has been compiled after taking into consideration a few important needs, such as:
Fast and responsive
Easy to install and use
Compatibility quotient across browsers
Robust and all round playlist options
Ability to include an advertisement at various stages of the video – before, during or after
Ability to integrate self-hosted videos with those from channels like YouTube, Dailymotion, Vimeo, etc.
Now that we have an idea what to look for, here is a list of the top 5 HTML5 Video Players.
VideoJS
VideoJS, an open source HTML5 video player is built using JavaScript and CSS. It's an HTML5 video player with optional support for Flash. Having Flash as a fallback option is especially helpful when you're using it on browsers that do not support HTML5. It can extend its support to Vimeo and YouTube.
Launched in the year 2010, VideoJS currently serves more than 400,000 websites across the internet. VideoJS is equally compatible on mobile devices as well as desktops.
Some of the top features of VideoJS include:
Plugin Support: VideoJS supports multiple plugins like analytics, advertising, playlists as well as support for advanced formats such as HLS and DASH. A full list of supported plugins can be found VideoJS plugin page.
Skinning: Everything about VideoJS is customizable. You can easily customize the way it looks by editing the CSS style. Steve Heffernan has a codepen demo for customizing VideoJS skin that should help you get started.
Ready adaptability to various plugins makes this player much more useful. Some sample plugins include:
Analytics: Ability to track Google Analytics events from the VideoJS player
Brand: You can add the logo of your brand to the player
Playlist: Support for playlists
Chromecast: Ability to cast a video to a device using a Chromecast device
JW Player
JW Player has been around for ages and was one of the most popular Flash video players for the web. Later on, it extended its support for HTML5 video playback. JW Player is completely customizable, has a responsive HTML5 video and has a large variety of features right from analytics support to accessibility and full HTML5 video controls.
It has perhaps the best website video player with its wide array of video supported solutions. JW player also works very well as an HTML5 video player for WordPress websites. It can also be used as an alternate option for YouTube's video player. Interestingly, before Google purchased YouTube, the original YouTube video player was based on JW Player.
One of the key reasons that the JW Player is above its peers in this category because of the sheer amount of features it provides via a number of different add-ons. These can range from advertising partnerships to closed captions as well as popular social networking tools.
As mentioned earlier, the player is completely customizable and supports a number of custom user-defined themes. It also comes with an integrated API. It has a number of different plugins to support the more popular CMSs, which makes integration fairly simple.
Kaltura HTML5 Video Player
Kaltura Player is a free-to-use, open source HTML5 video player that can be used to create multiple and custom inter-browser and inter-device skins that can match or complement the design of your website. The Kaltura player comes with numerous player templates to choose from.
Some of the key features include:
Robust, all-round Performance
Multi-platform support
Advertising & Analytics: It supports most ad formats including VAST v. 3.0 as well as integrated plugins that can be used across a wide range of video ad networks. These include Google's Doubleclick Ad Platform, FreeWheel, Eye Wonder, Ad Tech, Tremor Video, AdapTV and many more.
Flowplayer
Flowplayer is an extremely simple video player for creators who wish to include video playback on their websites. Integrating and the markup process for Flowplayer is decidedly straightforward, which is one of its major benefits.
At the outset, it is important to note that Flowplayer is primarily aimed at those creators who host video files independently. In case creators are using a streaming service such as Vimeo or YouTube, both streaming services provide code that can be used to embed the player itself onto the website or landing page.
Flowplayer is 100% customizable as well as skinnable and comes with support for including subtitles, modifying the playback speed, including video analytics and monetization opportunities.
The post 5 Great HTML5 Video Players appeared first on SitePoint.
30/07/2018
Speed Up Your WordPress Website with YOOtheme Pro https://www.sitepoint.com/speed-up-your-wordpress-website-with-yootheme-pro/
This article was created in partnership with YOOtheme. Thank you for supporting the partners who make SitePoint possible.
Starting July 2018, Google started ranking their mobile search results according to mobile page speed. This makes PageSpeed optimization even more important than before. Fortunately, there are tools that can help you speed-up your website. YOOtheme Pro, a new WordPress theme and page builder, ensures a high page speed ranking of your website thanks to its small, clean code base and the use of latest web technologies. Here is how it works.
What is YOOtheme Pro?
For those of you who are not familiar with YOOtheme Pro, it is a powerful theme and page builder for WordPress and Joomla. These are its main features:
Intuitive drag & drop page builder
Element Library with 30+ elements (including Slider, Slideshow, etc.)
Layout Library with 100+ pre-built premium layouts
Style Library with 70+ handcrafted styles
Integrated Unsplash Library
WooCommerce support
Footer Builder
Fast and lightweight code base
How does YOOtheme Pro speed up your website?
YOOtheme Pro is built with the JavaScript library Vue.js and the front-end framework UIkit. Thanks to these two libraries, YOOtheme Pro is extremely modular and extendable, and its fast and lightweight JavaScript provides a great user experience. The page builder generates small, clean and semantic markup, which is optimized for fast loading times. So let's take a closer look at the technologies YOOtheme Pro uses to speed up your browser's rendering time.
Lazy Loading Images
Images make up most of your website's total size, which can significantly impact the loading times. To improve page speed and decrease server traffic, YOOtheme Pro uses lazy loading. This means that initially only above-the-fold images are fully loaded. Other images are loaded as they enter the viewport. To prevent content from jumping, an empty placeholder image is generated instantly. Your visitors will not even notice that images are lazy loaded, and the first meaningful paint will get faster on the screen. You can also lazy load video elements.
Auto-generated srcsets
To make sure you get the best resolution on every device, YOOtheme Pro auto-generates srcsets. These are multiple versions of the same image in different sizes each used for a specific device. When you upload an image in YOOtheme Pro’s page builder and set a width or a height value, YOOtheme Pro generates seven srcset images. The first two are 100% and 200% of the target size. Other five images have the most frequently used device resolutions: 768, 1024, 1366, 1600 and 1920. Of course, these are only generated if the image size allows it, which is why you should always upload images with the highest resolution possible. This feature will guarantee the best user experience from mobiles to retina displays.
While srcsets really improve performance, they are usually not served for background images used as section or column backgrounds. These images extend to the full width and are often quite large, so loading them on mobiles takes a lot of bandwidth. To solve this problem, YOOtheme Pro also generates srcsets for background images, which is great for your mobile page speed rank.
Next-gen Image Format
To save bandwidth, Google also recommends using next-generation image formats like WebP. This format has a superior compression and quality characteristics as compared to the most common used image formats JPEG and PNG. Using WebPs saves size and consumes less cellular data. YOOtheme Pro automatically generates and serves images in WebP format for Chrome browsers. In case a visitor uses other browsers, the original JPEG or PNG images will be served.
Local Google Fonts
YOOtheme Pro stores Google Fonts locally. When you select a Google font in YOOtheme Pro, the `woff` and `woff2` font files are downloaded to your server and included into the CSS. This is not only helps with GDPR compliance, but it also largely improves the speed of your website since there is no round-trip to Google servers anymore. And if your web server supports HTTP/2, there is no round-trip at all.
Other Advanced Features
Apart from providing a fast user experience, YOOtheme Pro is also very developer-friendly. It allows you to override and extend everything, add custom elements, CSS, JavaScript and even create new theme settings. YOOtheme offers an extensive documentation on YOOtheme Pro, which includes a section specifically written for developers. There you will find information, tutorials and examples on custom assets, child themes, custom elements and much more.
Conclusion
As you can see, YOOtheme Pro is a very versatile theme and page builder for WordPress that really cares about speed. It integrates more optimizations for your Google PageSpeed rank than any other page builder on the WordPress market right now. It is a great tool for designers that gives them the power to create with none of the coding. But it was also built with developers in mind giving them the possibility to customize everything. YOOtheme Pro regularly releases theme packages on a particular topic including a thought-through content structure. Beautiful layouts, various styles and free-to-use images along with regular feature updates make YOOtheme Pro the next WordPress theme and page builder to watch for. So get YOOtheme Pro and try it out for yourself.
The post Speed Up Your WordPress Website with YOOtheme Pro appeared first on SitePoint.
26/07/2018
Build a Basic CRUD App with Node and React https://www.sitepoint.com/build-a-basic-crud-app-with-node-and-react/
This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
There are a lot of JavaScript frameworks out there today. It seems like I hear about a new one every month or so. They all have their advantages and are usually there to solve some sort of problem with an existing framework. My favorite to work with so far has been React. One of the best things about it is how many open source components and libraries there are in the React ecosystem, so you have a lot to choose from. This can be really difficult if you’re indecisive, but if you like the freedom to do things your way then React may be the best option for you.
In this tutorial, I’ll walk you through creating both a frontend web app in React and a backend REST API server in Node. The frontend will have a home page and a posts manager, with the posts manager hidden behind secure user authentication. As an added security measure, the backend will also not let you create or edit posts unless you’re properly authenticated.
The tutorial will use Okta’s OpenID Connect (OIDC) to handle authentication. On the frontend, the Okta React SDK will be used to request a token and provide it in requests to the server. On the backend, the Okta JWT Verifier will ensure that the user is properly authenticated, and throw an error otherwise.
The backend will be written with Express as a server, with Sequelize for modeling and storing data, and Epilogue for quickly creating a REST API without a lot of boilerplate.
Why React?
React has been one of the most popular JavaScript libraries for the past few years. One of the biggest concepts behind it, and what makes it so fast, is to use a virtual DOM (the Document Object Model, or DOM, is what describes the layout of a web page) and make small updates in batches to the real DOM. React isn’t the first library to do this, and there are quite a few now, but it certainly made the idea popular. The idea is that the DOM is slow, but JavaScript is fast, so you just say what you want the final output to look like and React will make those changes to the DOM behind the scenes. If no changes need to be made, then it doesn’t affect the DOM. If only a small text field changes, it will just patch that one element.
React is also most commonly associated with JSX, even though it’s possible to use React without JSX. JSX lets you mix HTML in with your JavaScript. Rather than using templates to define the HTML and binding those values to a view model, you can just write everything in JavaScript. Values can be plain JavaScript objects, instead of strings that need to be interpreted. You can also write reusable React components that then end up looking like any other HTML element in your code.
Here’s an example of some JSX code, that should be fairly simple to follow:
const Form = () => (
Name
Answer to life, the universe, and everything
);
const App = () => (
Welcome, Hitchhiker!
);
…and here’s what the same code would look like if you wrote it in plain JavaScript, without using JSX:
const Form = () => React.createElement(
"form",
null,
React.createElement(
"label",
null,
"Name",
React.createElement("input", { value: "Arthur Dent" })
),
React.createElement(
"label",
null,
"Answer to life, the universe, and everything",
React.createElement("input", { type: "number", value: 42 })
)
);
const App = () => React.createElement(
"main",
null,
React.createElement(
"h1",
null,
"Welcome, Hitchhiker!"
),
React.createElement(Form, null)
);
I find the JSX form much easier to read, but that’s just like, you know, my opinion, man.
Create Your React App
The quickest way to get started with React is to use Create React App, a tool that generates a progressive web app (PWA) with all the scripts and boilerplate tucked away neatly behind something called react-scripts, so you can just focus on writing code. It has all kinds of nice dev features as well, like updating the code whenever you make changes, and scripts to compile it down for production. You can use npm or yarn, but I’ll be using yarn in this tutorial.
To install create-react-app and yarn, simply run:
npm i -g [email protected] [email protected]
NOTE: I’ll be adding version numbers to help future-proof this post. In general though, you’d be fine leaving out the version numbers (e.g. npm i -g create-react-app).
Now bootstrap your application with the following commands:
create-react-app my-react-app
cd my-react-app
yarn start
The default app should now be running on port 3000. Check it out at http://localhost:3000.
Create a Basic Homepage in React with Material UI
To keep things looking nice without writing a lot of extra CSS, you can use a UI framework. Material UI is a great framework for React that implements Google’s Material Design principles.
Add the dependency with:
yarn add -ui/[email protected]
Material recommends the Roboto font. You can add it to your project by editing public/index.html and adding the following line inside the head tag:
You can separate components into separate files to help keep things organized. First, create a couple new folders in your src directory: components, and pages
mkdir src/components
mkdir src/pages
Now create an AppHeader component. This will serve as the navbar with links to pages, as well as show the title and whether you’re logged in.
src/components/AppHeader.js
import React from 'react';
import {
AppBar,
Toolbar,
Typography,
} from '-ui/core';
const AppHeader = () => (
My React App
);
export default AppHeader;
Also create a homepage:
src/pages/Home.js
import React from 'react';
import {
Typography,
} from '-ui/core';
export default () => (
Welcome Home!
);
Now go ahead and actually just gut the sample app, replacing src/App.js with the following:
src/App.js
import React, { Fragment } from 'react';
import {
CssBaseline,
withStyles,
} from '-ui/core';
import AppHeader from './components/AppHeader';
import Home from './pages/Home';
const styles = theme => ({
main: {
padding: 3 * theme.spacing.unit,
[theme.breakpoints.down('xs')]: {
padding: 2 * theme.spacing.unit,
},
},
});
const App = ({ classes }) => (
);
export default withStyles(styles)(App);
Material UI uses JSS (one of many flavors in the growingly popular trend of CSS in JavaScript), which is what withStyles provides.
The CssBaseline component will add some nice CSS defaults to the page (e.g. removing margins from the body), so we no longer need src/index.css. You can get rid of a couple other files too, now that we’ve gotten rid of most of the Hello World demo app.
rm src/index.css src/App.css src/logo.svg
In src/index.js, remove the reference to index.css (the line that says import './index.css';). While you’re at it, add the following as the very last line of src/index.js to turn on hot module reloading, which will make it so that changes you make automatically update in the app without needing to refresh the whole page:
if (module.hot) module.hot.accept();
At this point, your app should look like this:
Add Authentication to Your Node + React App with Okta
You would never ship your new app out to the Internet without secure identity management, right? Well, Okta makes that a lot easier and more scalable than what you’re probably used to. Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:
Authenticate and authorize your users
Store data about your users
Perform password-based and social login
Secure your application with multi-factor authentication
And much more! Check out our product documentation
If you don’t already have one, sign up for a forever-free developer account. Log in to your developer console, navigate to Applications, then click Add Application. Select Single-Page App, then click Next.
Since Create React App runs on port 3000 by default, you should add that as a Base URI and Login Redirect URI. Your settings should look like the following:
Click Done to save your app, then copy your Client ID and paste it as a variable into a file called .env.local in the root of your project. This will allow you to access the file in your code without needing to store credentials in source control. You’ll also need to add your organization URL (without the -admin suffix). Environment variables (other than NODE_ENV) need to start with REACT_APP_ in order for Create React App to read them, so the file should end up looking like this:
env.local
REACT_APP_OKTA_CLIENT_ID={yourClientId}
REACT_APP_OKTA_ORG_URL=https://{yourOktaDomain}
The easiest way to add Authentication with Okta to a React app is to use Okta’s React SDK. You’ll also need to add routes, which can be done using React Router. I’ll also have you start adding icons to the app (for now as an avatar icon to show you’re logged in). Material UI provides Material Icons, but in another package, so you’ll need to add that too. Run the following command to add these new dependencies:
yarn add /[email protected] [email protected] -ui/[email protected]
For routes to work properly in React, you need to wrap your whole application in a Router. Similarly, to allow access to authentication anywhere in the app, you need to wrap the app in a Security component provided by Okta. Okta also needs access to the router, so the Security component should be nested inside the router. You should modify your src/index.js file to look like the following:
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Security } from '/okta-react';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
const oktaConfig = {
issuer: `${process.env.REACT_APP_OKTA_ORG_URL}/oauth2/default`,
redirect_uri: `${window.location.origin}/implicit/callback`,
client_id: process.env.REACT_APP_OKTA_CLIENT_ID,
};
ReactDOM.render(
,
document.getElementById('root'),
);
registerServiceWorker();
if (module.hot) module.hot.accept();
Now in src/App.js you can use Routes. These tell the app to only render a certain component if the current URL matches the given path. Replace your Home component with a route that only renders the component when pointing at the root URL (/), and renders Okta’s ImplicitCallback component for the /implicit/callback path.
src/App.js
--- a/src/App.js
+++ b/src/App.js
@@ -1,4 +1,6 @@
import React, { Fragment } from 'react';
+import { Route } from 'react-router-dom';
+import { ImplicitCallback } from '/okta-react';
import {
CssBaseline,
withStyles,
@@ -21,7 +23,8 @@ const App = ({ classes }) => (
-
+
+
);
Next, you need a login button. This file is a bit bigger because it contains some logic to check if the user is authenticated. I’ll show you the whole component first, then walk through what each section is doing:
src/components/LoginButton.js
import React, { Component } from 'react';
import {
Button,
IconButton,
Menu,
MenuItem,
ListItemText,
} from '-ui/core';
import { AccountCircle } from '-ui/icons';
import { withAuth } from '/okta-react';
class LoginButton extends Component {
state = {
authenticated: null,
user: null,
menuAnchorEl: null,
};
componentDidUpdate() {
this.checkAuthentication();
}
componentDidMount() {
this.checkAuthentication();
}
async checkAuthentication() {
const authenticated = await this.props.auth.isAuthenticated();
if (authenticated !== this.state.authenticated) {
const user = await this.props.auth.getUser();
this.setState({ authenticated, user });
}
}
login = () => this.props.auth.login();
logout = () => {
this.handleMenuClose();
this.props.auth.logout();
};
handleMenuOpen = event => this.setState({ menuAnchorEl: event.currentTarget });
handleMenuClose = () => this.setState({ menuAnchorEl: null });
render() {
const { authenticated, user, menuAnchorEl } = this.state;
if (authenticated == null) return null;
if (!authenticated) return Login;
const menuPosition = {
vertical: 'top',
horizontal: 'right',
};
return (
);
}
}
export default withAuth(LoginButton);
React components have a concept of state management. Each component can be passed props (in a component like , type and number would be considered props). They can also maintain their own state, which has some initial values and can be changed with a function called setState. Any time the props or state changes, the component will rerender, and if changes need to be made to the DOM they will happen then. In a component, you can access these with this.props or this.state, respectively.
Here, you’re creating a new React component and setting the initial state values. Until you query the auth prop, you don’t know whether there’s a user or not, so you set authenticated and user to null. Material UI will use menuAnchorEl to know where to anchor the menu that lets you log the user out.
class LoginButton extends Component {
state = {
authenticated: null,
user: null,
menuAnchorEl: null,
};
// ...
}
React components also have their own lifecycle methods, which are hooks you can use to trigger actions at certain stages of the component lifecycle. Here, when the component is first mounted you’ll check to see whether or not the user has been authenticated, and if so get some more details about the user, such as their name and email address. You also want to rerun this check whenever the component updates, but you need to be careful to only update the state when something is different, otherwise you’ll get yourself into an infinite loop (the component updates, so you give the component new values, which updates the component, you give it new values, etc.). The withAuth function is a Higher Order Component (HOC) which wraps the original component and returns another one containing the auth prop.
class LoginButton extends Component {
// ...
componentDidUpdate() {
this.checkAuthentication();
}
componentDidMount() {
this.checkAuthentication();
}
async checkAuthentication() {
const authenticated = await this.props.auth.isAuthenticated();
if (authenticated !== this.state.authenticated) {
const user = await this.props.auth.getUser();
this.setState({ authenticated, user });
}
}
// ...
}
export default withAuth(LoginButton);
The following functions are helper functions used later to log the user in or out, and open or close the menu. Writing the function as an arrow function ensures that this is referring to the instantiation of the component. Without this, if a function is called somewhere outside of the component (e.g. in an onClick event), you would lose access to the component and wouldn’t be able to execute functions on it or access props or state.
class LoginButton extends Component {
// ...
login = () => this.props.auth.login();
logout = () => {
this.handleMenuClose();
this.props.auth.logout();
};
handleMenuOpen = event => this.setState({ menuAnchorEl: event.currentTarget });
}
All React components must have a render() function. This is what tells React what to display on the screen, even if it shouldn’t display anything (in which case you can return null).
When you’re not sure of the authentication state yet, you can just return null so the button isn’t rendered at all. Once Okta this.props.auth.isAuthenticated() returns, the value will either be true or false. If it’s false, you’ll want to provide a Login button. If the user is logged in, you can instead display an avatar icon that has a dropdown menu with a Logout button.
class LoginButton extends Component {
// ...
render() {
const { authenticated, user, menuAnchorEl } = this.state;
if (authenticated == null) return null;
if (!authenticated) return Login;
const menuPosition = {
vertical: 'top',
horizontal: 'right',
};
return (
);
}
}
The next piece of the puzzle is to add this LoginButton component to your header. In order to display it on the right-hand side of the page, you can put an empty spacer div that has a flex value of 1. Since the other objects aren’t told to flex, the spacer will take up as much space as it can. Modify your src/components/AppHeader.js file like so:
src/components/AppHeader.js
--- a/src/components/AppHeader.js
+++ b/src/components/AppHeader.js
@@ -3,16 +3,27 @@ import {
AppBar,
Toolbar,
Typography,
+ withStyles,
} from '-ui/core';
-const AppHeader = () => (
+import LoginButton from './LoginButton';
+
+const styles = {
+ flex: {
+ flex: 1,
+ },
+};
+
+const AppHeader = ({ classes }) => (
My React App
+
+
);
-export default AppHeader;
+export default withStyles(styles)(AppHeader);
You should now be able to log in and out of your app using the button in the top right.
When you click the Login button, you’ll be redirected to your Okta organization URL to handle authentication. You can log in with the same credentials you use in your developer console.
Once successfully signed in, you’re returned back to your app and should now see an icon showing that you’re logged in. If you click on the icon, you’ll see your name in a logout button. Clicking the button keeps you on the homepage but logs you out again.
Add a Node REST API Server
Now that users can securely authenticate, you can build the REST API server to perform CRUD operations on a post model. You’ll need to add quite a few dependencies to your project at this point:
yarn add /[email protected] [email protected] [email protected] [email protected] [email protected] express @4.16.3 [email protected] [email protected]
yarn add -D [email protected]
Create a new folder for the server under the src directory:
mkdir src/server
Now create a new file src/server/index.js. To keep this simple we will just use a single file, but you could have a whole subtree of files in this folder. Keeping it in a separate folder lets you watch for changes just in this subdirectory and reload the server only when making changes to this file, instead of anytime any file in src changes. Again, I’ll post the whole file and then explain some key sections below.
src/server/index.js
require('dotenv').config({ path: '.env.local' });
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Sequelize = require('sequelize');
const epilogue = require('epilogue');
const OktaJwtVerifier = require('/jwt-verifier');
const oktaJwtVerifier = new OktaJwtVerifier({
clientId: process.env.REACT_APP_OKTA_CLIENT_ID,
issuer: `${process.env.REACT_APP_OKTA_ORG_URL}/oauth2/default`,
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(async (req, res, next) => {
try {
if (!req.headers.authorization) throw new Error('Authorization header is required');
const accessToken = req.headers.authorization.trim().split(' ')[1];
await oktaJwtVerifier.verifyAccessToken(accessToken);
next();
} catch (error) {
next(error.message);
}
});
const database = new Sequelize({
dialect: 'sqlite',
storage: './test.sqlite',
});
const Post = database.define('posts', {
title: Sequelize.STRING,
body: Sequelize.TEXT,
});
epilogue.initialize({ app, sequelize: database });
epilogue.resource({
model: Post,
endpoints: ['/posts', '/posts/:id'],
});
const port = process.env.SERVER_PORT || 3001;
database.sync().then(() => {
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
});
The following loads the environment variables we used in the React app. This way we can use the same env variables, and only have to set them in one place.
require('dotenv').config({ path: '.env.local' });
This sets up the HTTP server and adds some settings to allow for Cross-Origin Resource Sharing (CORS) and will automatically parse JSON.
const app = express();
app.use(cors());
app.use(bodyParser.json());
Here is where you check that a user is properly authenticated. First, throw an error if there is no Authorization header, which is how you will send the authorization token. The token will actually look like Bearer aLongBase64String. You want to pass the Base 64 string to the Okta JWT Verifier to check that the user is properly authenticated. The verifier will initially send a request to the issuer to get a list of valid signatures, and will then check locally that the token is valid. On subsequent requests, this can be done locally unless it finds a claim that it doesn’t have signatures for yet.
If everything looks good, the call to next() tells Express to go ahead and continue processing the request. If however, the claim is invalid, an error will be thrown. The error is then passed into next to tell Express that something went wrong. Express will then send an error back to the client instead of proceeding.
app.use(async (req, res, next) => {
try {
if (!req.headers.authorization) throw new Error('Authorization header is required');
const accessToken = req.headers.authorization.trim().split(' ')[1];
await oktaJwtVerifier.verifyAccessToken(accessToken);
next();
} catch (error) {
next(error.message);
}
});
Here is where you set up Sequelize. This is a quick way of creating database models. You can Sequelize with a wide variety of databases, but here you can just use SQLite to get up and running quickly without any other dependencies.
const database = new Sequelize({
dialect: 'sqlite',
storage: './test.sqlite',
});
const Post = database.define('posts', {
title: Sequelize.STRING,
body: Sequelize.TEXT,
});
Epilogue works well with Sequelize and Express. It binds the two together like glue, creating a set of CRUD endpoints with just a couple lines of code. First, you initialize Epilogue with the Express app and the Sequelize database model. Next, you tell it to create your endpoints for the Post model: one for a list of posts, which will have POST and GET methods; and one for individual posts, which will have GET, PUT, and DELETE methods.
epilogue.initialize({ app, sequelize: database });
epilogue.resource({
model: Post,
endpoints: ['/posts', '/posts/:id'],
});
The last part of the server is where you tell Express to start listening for HTTP requests. You need to tell sequelize to initialize the database, and when it’s done it’s OK for Express to start listening on the port you decide. By default, since the React app is using 3000, we’ll just add one to make it port 3001.
const port = process.env.SERVER_PORT || 3001;
database.sync().then(() => {
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
});
Now you can make a couple small changes to package.json to make it easier to run both the frontend and backend at the same time. Replace the default start script and add a couple others, so your scripts section looks like this:
The post Build a Basic CRUD App with Node and React appeared first on SitePoint.
Address
Telephone
Website
Alerts
Be the first to know and let us send you an email when Foxplx posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.
-
Want your business to be the top-listed Advertising & Marketing Company?