by via Awwwards - Sites of the day
"Mr Branding" is a blog based on RSS for everything related to website branding and website design, it collects its posts from many sites in order to facilitate the updating to the latest technology.
To suggest any source, please contact me: Taha.baba@consultant.com
Friday, September 22, 2017
The Ultimate Photography Cheat Sheet Every Photography Lover Needs
[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]
by Web Desk via Digital Information World
Thursday, September 21, 2017
How #Brands Use #Instagram Stories [Infographic]
[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]
by Web Desk via Digital Information World
Building a React Universal Blog App: Implementing Flux
In the first part of this miniseries, we started digging into the world of React to see how we could use it, together with Node.js, to build a React Universal Blog App.
In this second and last part, we'll take our blog to the next level by learning how to add and edit content. We'll also get into the real meat of how to easily scale our React Universal Blog App using React organizational concepts and the Flux pattern.
Break It Down for Me
As we add more pages and content to our blog, our routes.js file will quickly become big. Since it's one of React's guiding principles to break things up into smaller, manageable pieces, let's separate our routes into different files.
Open your routes.js file and edit it so that it'll have the following code:
// routes.js
import React from 'react'
import { Route, IndexRoute } from 'react-router'
// Store
import AppStore from './stores/AppStore'
// Main component
import App from './components/App'
// Pages
import Blog from './components/Pages/Blog'
import Default from './components/Pages/Default'
import Work from './components/Pages/Work'
import NoMatch from './components/Pages/NoMatch'
export default (
<Route path="/" data={AppStore.data} component={App}>
<IndexRoute component={Blog}/>
<Route path="about" component={Default}/>
<Route path="contact" component={Default}/>
<Route path="work" component={Work}/>
<Route path="/work/:slug" component={Work}/>
<Route path="/blog/:slug" component={Blog}/>
<Route path="*" component={NoMatch}/>
</Route>
)
We've added a few different pages to our blog and significantly reduced the size of our routes.js file by breaking the pages up into separate components. Moreover, note that we've added a Store by including AppStore, which is very important for the next steps in scaling out our React application.
The Store: the Single Source of Truth
In the Flux pattern, the Store is a very important piece, because it acts as the single source of truth for data management. This is a crucial concept in understanding how React development works, and one of the most touted benefits of React. The beauty of this discipline is that, at any given state of our app we can access the AppStore's data and know exactly what's going on within it. There are a few key things to keep in mind if you want to build a data-driven React application:
- We never manipulate the DOM directly.
- Our UI answers to data and data live in the store
- If we need to change out our UI, we can go to the store and the store will create the new data state of our app.
- New data is fed to higher-level components, then passed down to the lower-level components through
propscomposing the new UI, based on the new data received.
With those four points, we basically have the foundation for a one-way data flow application. This also means that, at any state in our application, we can console.log(AppStore.data), and if we build our app correctly, we'll know exactly what we can expect to see. You'll experience how powerful this is for debugging as well.
Now let's create a store folder called stores. Inside it, create a file called AppStore.js with the following content:
// AppStore.js
import { EventEmitter } from 'events'
import _ from 'lodash'
export default _.extend({}, EventEmitter.prototype, {
// Initial data
data: {
ready: false,
globals: {},
pages: [],
item_num: 5
},
// Emit change event
emitChange: function(){
this.emit('change')
},
// Add change listener
addChangeListener: function(callback){
this.on('change', callback)
},
// Remove change listener
removeChangeListener: function(callback) {
this.removeListener('change', callback)
}
})
You can see that we've attached an event emitter. This allows us to edit data in our store, then re-render our application using AppStore.emitChange(). This is a powerful tool that should only be used in certain places in our application. Otherwise, it can be hard to understand where AppStore data is being altered, which brings us to the next point…
React Components: Higher and Lower Level
Dan Abramov wrote a great post on the concept of smart and dumb components. The idea is to keep data-altering actions just in the higher-level (smart) components, while the lower-level (dumb) components take the data they're given through props and render UI based on that data. Any time there's an action performed on a lower-level component, that event is passed up through props to the higher-level components in order to be processed into an action. Then it redistributes the data (one-way data flow) back through the application.
Said that, let's start building some components. To do that, create a folder called components. Inside it, create a file called App.js with this content:
// App.js
import React, { Component } from 'react'
// Dispatcher
import AppDispatcher from '../dispatcher/AppDispatcher'
// Store
import AppStore from '../stores/AppStore'
// Components
import Nav from './Partials/Nav'
import Footer from './Partials/Footer'
import Loading from './Partials/Loading'
export default class App extends Component {
// Add change listeners to stores
componentDidMount(){
AppStore.addChangeListener(this._onChange.bind(this))
}
// Remove change listeners from stores
componentWillUnmount(){
AppStore.removeChangeListener(this._onChange.bind(this))
}
_onChange(){
this.setState(AppStore)
}
getStore(){
AppDispatcher.dispatch({
action: 'get-app-store'
})
}
render(){
const data = AppStore.data
// Show loading for browser
if(!data.ready){
document.body.className = ''
this.getStore()
let style = {
marginTop: 120
}
return (
<div className="container text-center" style={ style }>
<Loading />
</div>
)
}
// Server first
const Routes = React.cloneElement(this.props.children, { data: data })
return (
<div>
<Nav data={ data }/>
{ Routes }
<Footer data={ data }/>
</div>
)
}
}
In our App.js component, we've attached an event listener to our AppStore that will re-render the state when AppStore emits an onChange event. This re-rendered data will then be passed down as props to the child components. Also note that we've added a getStore method that will dispatch the get-app-store action to render our data on the client side. Once the data has been fetched from the Cosmic JS API, it will trigger an AppStore change that will include AppStore.data.ready set to true, remove the loading sign and render our content.
Page Components
To build the first page of our blog, create a Pages folder. Inside it, we'll create a file called Blog.js with the following code:
// Blog.js
import React, { Component } from 'react'
import _ from 'lodash'
import config from '../../config'
// Components
import Header from '../Partials/Header'
import BlogList from '../Partials/BlogList'
import BlogSingle from '../Partials/BlogSingle'
// Dispatcher
import AppDispatcher from '../../dispatcher/AppDispatcher'
export default class Blog extends Component {
componentWillMount(){
this.getPageData()
}
componentDidMount(){
const data = this.props.data
document.title = config.site.title + ' | ' + data.page.title
}
getPageData(){
AppDispatcher.dispatch({
action: 'get-page-data',
page_slug: 'blog',
post_slug: this.props.params.slug
})
}
getMoreArticles(){
AppDispatcher.dispatch({
action: 'get-more-items'
})
}
render(){
const data = this.props.data
const globals = data.globals
const pages = data.pages
let main_content
if(!this.props.params.slug){
main_content = <BlogList getMoreArticles={ this.getMoreArticles } data={ data }/>
} else {
const articles = data.articles
// Get current page slug
const slug = this.props.params.slug
const articles_object = _.keyBy(articles, 'slug')
const article = articles_object[slug]
main_content = <BlogSingle article={ article } />
}
return (
<div>
<Header data={ data }/>
<div id="main-content" className="container">
<div className="row">
<div className="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
{ main_content }
</div>
</div>
</div>
</div>
)
}
}
This page is going to serve as a template for our blog list page (home) and our single blog pages. Here we've added a method to our component that will get the page data prior to the component mounting using the React lifecycle componentWillMount method. Then, once the component has mounted at componentDidMount(), we'll add the page title to the <title> tag of the document.
Along with some of the rendering logic in this higher-level component, we've included the getMoreArticles method. This is a good example of a call to action that's stored in a higher-level component and made available to lower-level components through props.
Let's now get into our BlogList component to see how this works.
Create a new folder called Partials. Then, inside it, create a file called BlogList.js with the following content:
// BlogList.js
import React, { Component } from 'react'
import _ from 'lodash'
import { Link } from 'react-router'
export default class BlogList extends Component {
scrollTop(){
$('html, body').animate({
scrollTop: $("#main-content").offset().top
}, 500)
}
render(){
let data = this.props.data
let item_num = data.item_num
let articles = data.articles
let load_more
let show_more_text = 'Show More Articles'
if(data.loading){
show_more_text = 'Loading...'
}
if(articles && item_num <= articles.length){
load_more = (
<div>
<button className="btn btn-default center-block" onClick={ this.props.getMoreArticles.bind(this) }>
{ show_more_text }
</button>
</div>
)
}
articles = _.take(articles, item_num)
let articles_html = articles.map(( article ) => {
let date_obj = new Date(article.created)
let created = (date_obj.getMonth()+1) + '/' + date_obj.getDate() + '/' + date_obj.getFullYear()
return (
<div key={ 'key-' + article.slug }>
<div className="post-preview">
<h2 className="post-title pointer">
<Link to={ '/blog/' + article.slug } onClick={ this.scrollTop }>{ article.title }</Link>
</h2>
<p className="post-meta">Posted by <a href="https://cosmicjs.com" target="_blank">Cosmic JS</a> on { created }</p>
</div>
<hr/>
</div>
)
})
return (
<div>
<div>{ articles_html }</div>
{ load_more }
</div>
)
}
}
In our BlogList component, we've added an onClick event to our Show More Articles button. The latter executes the getMoreArticles method that was passed down as props from the higher-level page component. When that button is clicked, the event bubbles up to the Blog component and then triggers an action on the AppDispatcher. AppDispatcher acts as the middleman between our higher-level components and our AppStore.
For the sake of brevity, we're not going to build out all of the Page and Partial components in this tutorial, so please download the GitHub repo and add them from the components folder.
AppDispatcher
The AppDispatcher is the operator in our application that accepts information from the higher-level components and distributes actions to the store, which then re-renders our application data.
To continue this tutorial, create a folder named dispatcher. Inside it, create a file called AppDispatcher.js, containing the following code:
// AppDispatcher.js
import { Dispatcher } from 'flux'
import { getStore, getPageData, getMoreItems } from '../actions/actions'
const AppDispatcher = new Dispatcher()
// Register callback with AppDispatcher
AppDispatcher.register((payload) => {
let action = payload.action
switch(action) {
case 'get-app-store':
getStore()
break
case 'get-page-data':
getPageData(payload.page_slug, payload.post_slug)
break
case 'get-more-items':
getMoreItems()
break
default:
return true
}
return true
})
export default AppDispatcher
We've introduced the Flux module into this file to build our dispatcher. Let's add our actions now.
Continue reading %Building a React Universal Blog App: Implementing Flux%
by Tony Spiro via SitePoint
Dealing with Asynchronous APIs in Server-rendered React
If you've ever made a basic React app page, it probably suffered from poor SEO and performance issues on slower devices. You can add back traditional server-side rendering of web pages, typically with NodeJS, but this isn't a straightforward process, especially with asynchronous APIs.
The two main benefits you get from rendering your code on the server are:
- increased performance in load times
- improving the flexibility of your SEO.
Remember that Google does wait for your JavaScript to load, so simple things like title content will change without issue. (I can't speak for other search engines, though, or how reliable that is.)
In this post, I'll discuss getting data from asynchronous APIs when using server-rendered React code. React code has the entire structure of the app built in JavaScript. This means that, unlike traditional MVC patterns with a controller, you don't know what data you need until the app is rendered. With a framework like Create React App, you can quickly create a working app of very high quality, but it requires you to handle rendering only on the client. There's a performance issue with this, as well as an SEO/data issue, where traditional templating engines you can alter the head as you see fit.
The Problem
React renders synchronously for the most part, so if you don't have the data, you render a loading screen and wait for the data to come. This doesn't work so well from the server, because you don't know what you need until you've rendered, or you know what you need but you've already rendered.
Check out this stock-standard render method:
ReactDOM.render(
<provider store={store}>
<browserrouter>
<app></app>
</browserrouter>
</provider>
, document.getElementById('root')
)
Issues:
- It's a DOM render looking for a root element. This doesn't exist on my server, so we have to separate that.
- We don't have access to anything outside our main root element. We can't set Facebook tags, title, description, various SEO tags, and we don't have control over the rest of the DOM outside the element, especially the head.
- We're providing some state, but the server and client have different states. We need to consider how to handle that state (in this case, Redux).
So I've used two libraries here, and they're pretty popular, so hopefully it carries over to the other libraries you're using.
Redux: Storing state where your server and client are synced is a nightmare issue. It's very costly, and usually leads to complex bugs. On the server side, ideally, you don't want to do anything with Redux apart from just enough to get things working and rendering correctly. (You can still use it as normal; just set enough of the state to look like the client.) If you want to try, check out the various distributed systems guides as a starting point.
React-Router: FYI, this is the v4 version, which is what is installed by default, but it's significantly different if you've got an older existing project. You need to make sure you handle your routing server side and client side and with v4 --- and it's very good at this.
After all, what if you need to make a database call? Suddenly this becomes a big issue, because it's async and it's inside your component. Of course, this isn't a new issue: check it out on the official React repo.
You have to render in order to determine what dependencies you need --- which need to be determined at runtime --- and to fetch those dependencies before serving to your client.
Existing Solutions
Below, I'll review the solutions that are currently on offer to solve this problem.
Next.js
Before we go anywhere, if you want production, server-side-rendered React code or universal app, Next.js] is where you want to go. It works, it's clean, and it's got Zeit backing it.
However, it's opinionated, you have to use their toolchain, and the way they handle async data loading isn't necessarily that flexible.
Check out this direct copy from the Next.js repo documentation:
import React from 'react'
export default class extends React.Component {
static async getInitialProps ({ req }) {
return req
? { userAgent: req.headers['user-agent'] }
: { userAgent: navigator.userAgent }
}
render () {
return <div>
Hello World {this.props.userAgent}
</div>
}
}
getInitialProps is the key there, which returns a promise that resolves to an object that populates props, and only on a page. What's great is that's just built in to their toolchain: add it and it works, no work required!
So how do you get database data? You make an api call. You don't want to? Well, that's too bad. (Okay, so you can add custom things, but you have to fully implement it yourself.) If you think about this, though, it's a very reasonable and, generally speaking, good practice, because otherwise, your client would still be making the same API call, and latency on your server is virtually negligible.
You're also limited in what you have access to --- pretty much just the request object; and again, this seems like good practice, because you don't have access to your state, which would be different on your server versus client anyways. Oh, and in case you didn't catch it before, it only works on top-level page components.
Redux Connect
Redux Connect is a very opinionated server-side renderer, with a decent philosophy, but if you don't use all the tools they describe, this might not be for you. There's a lot to this package, but it's so complex and not yet upgraded to React Router v4. There's a lot of setup to this, but let's take the most important part, just to learn some lessons:
// 1. Connect your data, similar to react-redux @connect
@asyncConnect([{
key: 'lunch',
promise: ({ params, helpers }) => Promise.resolve({ id: 1, name: 'Borsch' })
}])
class App extends React.Component {
render() {
// 2. access data as props
const lunch = this.props.lunch
return (
<div>{lunch.name}</div>
)
}
}
Decorators aren't standard in JavaScript. They're Stage 2 at the time of writing, so use at your discretion. It's just another way of adding higher-order components. The idea is pretty simple: the key is for what to pass to your props, and then you have a list of promises, which resolve and are passed in. This seems pretty good. Perhaps an alternative is simply this:
@asyncConnect([{
lunch: ({ params, helpers }) => Promise.resolve({ id: 1, name: 'Borsch' })
}])
That seems doable with JavaScript without too many issues.
react-frontload
The react-frontload repo doesn't have a lot of documentation, or explanation, but perhaps the best understanding I could get was from the tests (such as this one)
and just reading the source code. When something is mounted, it's added to a promise queue, and when that resolves, it's served. What it does is pretty good, though it's hard to recommend something that's not well documented, maintained or used:
const App = () => (
<frontload isServer >
<component1 entityId='1' store={store}></component1>
</frontload>
)
return frontloadServerRender(() => (
render(<app></app>)
)).then((serverRenderedMarkup) => {
console.log(serverRenderedMarkup)
})
Continue reading %Dealing with Asynchronous APIs in Server-rendered React%
by Roger Jin via SitePoint
How to Secure Your WordPress Site from the DDoS Attack Onslaught
This article was sponsored by Incapsula. Thank you for supporting the partners who make SitePoint possible.
Distributed denial of service (DDoS) attacks are rapidly ramping in scale. They’ve been on the radar since at least 2000, and 2017 may be the year they become your biggest security concern. If you don’t have a DDoS strategy in place, it’s time to choose one.
Based on current trends, industry experts predict that this may be a crisis year. That’s reflected in recent headlines like these:
- DDoS in 2017: Strap yourself in for a bumpy ride, The Register.
- DDoS attacks up 380% in Q1 2017, CIO Dive
- The 2017 DDoS tsunami will cost companies millions, TechRepublic
- Hackers take no holidays: 2017 DDoS attacks rise fivefold, SiliconANGLE
- Expect an increase in ransomware and DDoS attack combos in 2017, Enterprise Innovation
- 2017 may be crisis year for DDoS attacks, ComputerWeekly.
The more popular a platform is, the more likely it will become a target for attacks, and WordPress is the most popular platform on the internet. In a previous post we outlined 48 ways to keep your WordPress site secure. By all means keep your WordPress patched and updated, but that won’t protect you from the zombie hoards. You need a targeted DDoS solution you can trust.
How do DDoS attacks work? And what is the most effective way to guard your WordPress site?
The Rapid Growth of the DDoS Threat
DDoS attacks use your site’s bandwidth limitations against you. How many visitors can it handle at once? Too many, and it will become overwhelmed and unresponsive, just like when hundreds of customers walk into a physical shop at the same time. A DDoS attack simulates exactly that.
A DDoS attack is equivalent to hundreds of thousands of fake customers converging on a traditional shop at the same time. The shop quickly becomes overwhelmed. The genuine customers cannot get in and the shop is unable to trade as it cannot serve them. (Deloitte Predictions 2017)
For an online store or website, those fake visitors are often members of a botnet—a network of hundreds of thousands of compromised devices that are being controlled by a third party. Those devices may include:
- older PCs running less secure, unpatched operating systems like Windows XP
- compromised smartphones and other mobile, internet-connected devices
- smart devices such as thermostats, TVs, refrigerators, cameras and even light bulbs—commonly referred to as IoT (“the internet of things”)
- and fake IP addresses spoofed by compromised servers.
Combined, these devices can send gigabits of garbage data to your server each second, and right now the scale of the onslaught is exploding. Late last year The Hacker News site reported the first 1 Tbps DDoS attack powered by 150,000 hacked IoT devices, and Deloitte predicts there will be ten similar attacks this year.
Why is 2017 such a turning point? Several trends are converging to create the perfect storm:
- There are more IoT devices than ever, and they’re easy to incorporate into botnets.
- There is more bandwidth available than ever, and it can be used to spew junk data at your website.
- New DDoS strategies cause more damage with less bandwidth by hitting web applications, and there’s more of them than ever.
- Malware tools, like Mirai, are easier to use than ever, and DDoS-for-hire services are more accessible than ever, costing as little as $5.
DDoS-for-hire is going to ramp up. The IoT botnets, combined with an easy money-making opportunity, will bring more of this kind of thing in 2017. Sceptical? Well, there’s already a 400,000 strong IoT zombie army for rent, using the Mirai malware. (The Register)
How can you protect your site from a massive attack of unwanted visitors? Take a lesson from the nightclubs, and call in a bouncer. The key is to deal with the threat before it reaches your door.
Continue reading %How to Secure Your WordPress Site from the DDoS Attack Onslaught%
by Adrian Try via SitePoint
7 #Internet Safety Tips Every Parent Must Show Their Child! [infographic]
[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]
by Web Desk via Digital Information World