Building Skeleton Components with React

One of the advantages of building a Single Page Application (SPA) is the way navigating between pages is extremely fast. Unfortunately, the data of our components is sometimes only available after we have navigated to a specific part of our application. We can level up the user’s perceived performance by breaking the component into two pieces: the container (which displays a skeleton view when it’s empty) and the content. If we delay the rendering of the content component until we …
The post Building Skeleton Components with React appeared first on CSS-Tricks.

Link: https://css-tricks.com/building-skeleton-components-with-react/

Build a Simple Web App with Express, React and GraphQL

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
GraphQL and React have both become quite popular in the last few years, and it’s safe to say they go together like avocado and toast. A GraphQL server can be written in Node and lets you easily create a flexible API using JavaScript classes and functions. When a frontend developer queries the server, only the information asked for gets processed. This means you can make the backend as robust as you want while keeping the frontend light by only requesting information needed for the page you’re viewing.
GraphQL is a relatively new standard for defining types and querying data, and there are quite a few different implementations of it, both server-side and client-side. Today I’ll show you how to use Express to create a GraphQL server, as well as how to create a single-page app in React that uses Apollo’s client to query the server.
Create the React App
The quickest way to get started with a React app is to use Create React App. If you don’t already have Node, Yarn, and Create React App installed, you can run the following commands:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
npm install –global yarn create-react-app

Next, create and start a new app:
create-react-app graphql-express-react
cd graphql-express-react
yarn start

When you run create-react-app, you’ll get a new folder with everything you need to get started, and all the dependencies you need will be installed locally using yarn. When you type yarn start from within the folder, you’re starting the frontend development server that will automatically update whenever you edit any files.

Create the GraphQL Server
Before we continue writing the frontend, you’ll need a server to connect to. Run the following commands to install the dependencies you’ll need to get up and running:
yarn add express@4.16.3 cors@2.8.4 graphql@14.0.2 express-graphql@0.6.12 graphql-tag@2.9.2

Create a new directory in your project’s src folder, named server:
mkdir src/server

In there, create a new file named index.js, with the following code:
const express = require(‘express’);
const cors = require(‘cors’);
const graphqlHTTP = require(‘express-graphql’);
const gql = require(‘graphql-tag’);
const { buildASTSchema } = require(‘graphql’);

const POSTS = [
{ author: “John Doe", body: "Hello world" },
{ author: "Jane Doe", body: "Hi, planet!" },
];

const schema = buildASTSchema(gql`
type Query {
posts: [Post]
post(id: ID!): Post
}

type Post {
id: ID
author: String
body: String
}
`);

const mapPost = (post, id) => post && ({ id, …post });

const root = {
posts: () => POSTS.map(mapPost),
post: ({ id }) => mapPost(POSTS[id], id),
};

const app = express();
app.use(cors());
app.use(‘/graphql’, graphqlHTTP({
schema,
rootValue: root,
graphiql: true,
}));

const port = process.env.PORT || 4000
app.listen(port);
console.log(`Running a GraphQL API server at localhost:${port}/graphql`);

Let me explain the different parts of this code.
At the top of the file, you use the require tag to import your dependencies. Native Node doesn’t support the import tag yet, but you can use require instead. A future version of Node will likely support import. Create React App uses babel to transpile the code before running it, which allows you to use the import syntax in the React code, so you’ll see that when we get to the frontend code.
For now, this is just using some mock data, which is what the const POSTS contains. Each item contains an author and a body.
The gql tag allows your favorite code editor to realize that you’re writing GraphQL code so that it can stylize it appropriately. It also parses the string and converts it to GraphQL AST Abstract Syntax Tree. You then need to build a schema using buildASTSchema.
The GraphQL schema might be the most interesting part of this code. This is what defines the different types and allows you to say what the client can query. This will also automatically generate some very useful documentation so that you can just focus on coding.
type Query {
posts: [Post]
post(id: ID!): Post
}

type Post {
id: ID
author: String
body: String
}

Here, you’ve defined a Post type, which contains an id, and author, and a body. You need to say what the types are for each element. Here, author and body both use the primitive String type, and id is an ID.
The Query type is a special type that lets you query the data. Here, you’re saying that posts will give you an array of Posts, but if you want a single Post you can query it by calling post and passing in the ID.
const mapPost = (post, id) => post && ({ id, …post });

const root = {
posts: () => POSTS.map(mapPost),
post: ({ id }) => mapPost(POSTS[id], id),
};

You need to provide a set of resolvers to tell GraphQL how to handle the queries. When someone queries posts, it will run this function, providing an array of all the POSTS, using their index as an ID.
When you query post, it expects an id and will return the post at the given index.
const app = express();
app.use(cors());
app.use(‘/graphql’, graphqlHTTP({
schema,
rootValue: root,
graphiql: true,
}));

const port = process.env.PORT || 4000
app.listen(port);
console.log(`Running a GraphQL API server at localhost:${port}/graphql`);

Now you are able to create the server. The graphqlHTTP function creates an Express server running GraphQL, which expects the resolvers as rootValue, and the schema. The graphiql flag is optional and will run a server for you allowing you to more easily visualize the data and see the auto-generated documentation. When you run app.listen, you’re starting the GraphQL server.
To make sure we can easily run both the server and client at the same time, add the following dev dependencies:
yarn add -D nodemon@1.18.4 npm-run-all@4.1.3

Next, edit your package.json file so that the scripts section looks like this:
{
"start": "npm-run-all –parallel watch:server start:web",
"start:web": "react-scripts start",
"start:server": "node src/server",
"watch:server": "nodemon –watch src/server src/server",
"build": "react-scripts build",
"test": "react-scripts test –env=jsdom",
"eject": "react-scripts eject"
},

Close your existing web server, then simply type yarn start again to run both the server and client at the same time. Whenever you make changes to the server, just the server will restart. Whenever you make changes to the frontend code, the page should automatically refresh with the latest changes.
Point your browser to http://localhost:4000/graphql to get the GraphiQL server. You can always come back here and refresh after changing some code around in the server to see the latest Schema and test your queries.

Connect React to GraphQL
Next, you need to connect the frontend to GraphQL. I’ll use Bootstrap for some decent styling with minimal effort. Apollo makes a great React client that can link up to any GraphQL server. To install the dependencies you need for the frontend, run the following:
yarn add bootstrap@4.1.3 reactstrap@6.4.0 apollo-boost@0.1.16 react-apollo@2.1.11

You’ll need to configure the Apollo client to know where to connect to the backend. Create a new file src/apollo.js with the following code:
import ApolloClient from ‘apollo-boost’;

export default new ApolloClient({
uri: "http://localhost:4000/graphql",
});

In order for Apollo’s Query React component to be able to connect using the client, the entire app needs to be wrapped in an ApolloProvider component. You’ll also want to include the styling for Bootstrap, and you can get rid of the index.css file that came with Create React App now. Make the following changes to your src/index.js file:
@@ -1,8 +1,17 @@
import React from ‘react’;
import ReactDOM from ‘react-dom’;
-import ‘./index.css’;
+import { ApolloProvider } from ‘react-apollo’;
+
+import ‘bootstrap/dist/css/bootstrap.min.css’;
import App from ‘./App’;
import registerServiceWorker from ‘./registerServiceWorker’;
+import client from ‘./apollo’;

-ReactDOM.render(, document.getElementById(‘root’));
+ReactDOM.render(
+ <ApolloProvider client={client}>
+ <App />
+ </ApolloProvider>,
+ document.getElementById(‘root’)
+);
serviceWorker.unregister();
+if (module.hot) module.hot.accept();

The module.hot.accept() isn’t really necessary, but makes it so that just the components changing within the app will refresh as you update them, rather than refreshing the entire page. Every once in a while you may need to refresh just to reset the state of the app, but generally, this leads to a quicker turnaround time.
Create a new file src/PostViewer.js that will fetch the data and render it in a table:
import React from ‘react’;
import gql from ‘graphql-tag’;
import { Query } from ‘react-apollo’;
import { Table } from ‘reactstrap’;

export const GET_POSTS = gql`
query GetPosts {
posts {
id
author
body
}
}
`;

export default () => (
<Query query={GET_POSTS}>
{({ loading, data }) => !loading && (
<Table>
<thead>
<tr>
<th>Author</th>
<th>Body</th>
</tr>
</thead>
<tbody>
{data.posts.map(post => (
<tr key={post.id}>
<td>{post.author}</td>
<td>{post.body}</td>
</tr>
))}
</tbody>
</Table>
)}
</Query>
);

The Query component requires a GraphQL query. In this case, you’re just getting all of the posts with their ID and the author and body. The Query component also requires a render function as its only child. It provides a loading state, but in our case, we just won’t show anything while it’s loading, since it will be really quick to fetch the data locally. Once it’s done loading, the data variable will be an object including the data you requested.
The above code renders a table (Table is a component that includes all the Bootstrap classes you need to make it look pretty) with all of the posts.
You should now change your src/App.js file to include the PostViewer component you just made. It should look like this:
import React, { Component } from ‘react’;

import PostViewer from ‘./PostViewer’;

class App extends Component {
render() {
return (
<main>
<PostViewer />
</main>
);
}
}

export default App;

Now if you go to http://localhost:3000 you should see this:

Add the Ability to Edit Posts in GraphQL
In GraphQL, a query is typically read-only. If you want to modify data, you should use what’s known as a mutation instead.
Create a new Mutation type in your const schema in src/server/index.js to submit a post. You can create an input type to simplify your input variables. The new mutation should return the new Post on success:
type Mutation {
submitPost(input: PostInput!): Post
}

input PostInput {
id: ID
author: String!
body: String!
}

You’ll need to update your root variable to create a new resolver for submitPost as well. Add the following resolver:
submitPost: ({ input: { id, author, body } }) => {
const post = { author, body };
let index = POSTS.length;

if (id != null && id >= 0 && id < POSTS.length) {
if (POSTS[id].authorId !== authorId) return null;

POSTS.splice(id, 1, post);
index = id;
} else {
POSTS.push(post);
}

return mapPost(post, index);
},

If you provide an id, it will try to find the post at that index and replace the data with the author and body that was provided. Otherwise, it will add a new post. Then it returns the post you provided along with the new id for it. When you send a mutation request to GraphQL, you can define which pieces you want back:

For the frontend, you’ll need to create a new component for editing posts. Forms in React can be made easier by a library called Final Form. Install it with yarn:
yarn add final-form@4.10.0 react-final-form@3.6.5

Now, make a new file src/PostEditor.js and fill it with the following (I’ll explain it in more detail just below):
import React from ‘react’;
import gql from ‘graphql-tag’;
import {
Button,
Form,
FormGroup,
Label,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
} from ‘reactstrap’;
import { Form as FinalForm, Field } from ‘react-final-form’;

import client from ‘./apollo’;
import { GET_POSTS } from ‘./PostViewer’;

const SUBMIT_POST = gql`
mutation SubmitPost($input: PostInput!) {
submitPost(input: $input) {
id
}
}
`;

const PostEditor = ({ post, onClose }) => (
<FinalForm
onSubmit={async ({ id, author, body }) => {
const input = { id, author, body };

await client.mutate({
variables: { input },
mutation: SUBMIT_POST,
refetchQueries: () => [{ query: GET_POSTS }],
});

onClose();
}}
initialValues={post}
render={({ handleSubmit, pristine, invalid }) => (
<Modal isOpen toggle={onClose}>
<Form onSubmit={handleSubmit}>
<ModalHeader toggle={onClose}>
{post.id ? ‘Edit Post’ : ‘New Post’}
</ModalHeader>
<ModalBody>
<FormGroup>
<Label>Author</Label>
<Field
required
name="author"
className="form-control"
component="input"
/>
</FormGroup>
<FormGroup>
<Label>Body</Label>
<Field
required
name="body"
className="form-control"
component="input"
/>
</FormGroup>
</ModalBody>
<ModalFooter>
<Button type="submit" disabled={pristine} color="primary">Save</Button>
<Button color="secondary" onClick={onClose}>Cancel</Button>
</ModalFooter>
</Form>
</Modal>
)}
/>
);

export default PostEditor;

The submitPost mutation is the new mutation to connect to the backend. It can use the PostInput type defined in the server:
const SUBMIT_POST = gql`
mutation SubmitPost($input: PostInput!) {
submitPost(input: $input) {
id
}
}
`;

Final Form takes an onSubmit function that will pass in the data entered by the user. After the post is submitted, you’ll want to close the modal, so PostEditor takes an onClose prop to call when you’re done submitting.
Final Form also takes an initialValues object to define what values the form should initially have. In this case, the PostEditor component will take a post prop that has the variables you need in it, so that gets passed along as the initial values.
The other required prop is the render function, which will render the form. Final Form gives you a few useful form props so you can know if the form is valid or not, or if it’s been modified from the initialValues.
const PostEditor = ({ post, onClose }) => (
<FinalForm
onSubmit={/* … */}
initialValues={post}
render={/* … */}
/>
);

export default PostEditor;

In the onSubmit function, you’ll call the mutation needed to submit the post. Apollo lets you re-fetch queries. Since you know your list of posts will be out of date once you submit edits, you can re-fetch the GET_POSTS query here.
onSubmit={async ({ id, author, body }) => {
const input = { id, author, body };

await client.mutate({
variables: { input },
mutation: SUBMIT_POST,
refetchQueries: () => [{ query: GET_POSTS }],
});

onClose();
}}

The render function will display a Bootstrap modal. This PostEditor component will only be rendered when you want it to be open, so isOpen is just set to true. Here you also use the onClose prop to close the modal when the user clicks outside the modal, hits Esc, or clicks the Cancel button.
The form needs to have the handleSubmit function passed to it as an onSubmit prop. This tells the form to go through Final Form instead of sending a POST request to the page.
Final Form also handles all the boilerplate needed to have a controlled input. Instead of storing the data in state whenever the user types something, you can just use the Field component.
render={({ handleSubmit, pristine, invalid }) => (
<Modal isOpen toggle={onClose}>
<Form onSubmit={handleSubmit}>
<ModalHeader toggle={onClose}>
{post.id ? ‘Edit Post’ : ‘New Post’}
</ModalHeader>
<ModalBody>
<FormGroup>
<Label>Author</Label>
<Field
required
name="author"
className="form-control"
component="input"
/>
</FormGroup>
<FormGroup>
<Label>Body</Label>
<Field
required
name="body"
className="form-control"
component="input"
/>
</FormGroup>
</ModalBody>
<ModalFooter>
<Button type="submit" disabled={pristine} color="primary">Save</Button>
<Button color="secondary" onClick={onClose}>Cancel</Button>
</ModalFooter>
</Form>
</Modal>
)}

Next, you’ll have to make a couple small changes to your PostViewer. This adds a hook to each row so that you can determine whether the row should be editable or not and if so, changes the styles a bit and lets you click on the row. Clicking on the row calls another callback, which you can use to set which post is being edited.
diff –git a/src/PostViewer.js b/src/PostViewer.js
index 5c53b5a..84177e0 100644
— a/src/PostViewer.js
+++ b/src/PostViewer.js
@@ -13,7 +13,11 @@ export const GET_POSTS = gql`
}
`;

-export default () => (
+const rowStyles = (post, canEdit) => canEdit(post)
+ ? { cursor: ‘pointer’, fontWeight: ‘bold’ }
+ : {};
+
+const PostViewer = ({ canEdit, onEdit }) => (
<Query query={GET_POSTS}>
{({ loading, data }) => !loading && (
<Table>
@@ -25,7 +29,11 @@ export default () => (
</thead>
<tbody>
{data.posts.map(post => (
– <tr key={post.id}>
+ <tr
+ key={post.id}
+ style={rowStyles(post, canEdit)}
+ onClick={() => canEdit(post) && onEdit(post)}
+ >
<td>{post.author}</td>
<td>{post.body}</td>
</tr>
@@ -35,3 +43,10 @@ export default () => (
)}
</Query>
);
+
+PostViewer.defaultProps = {
+ canEdit: () => false,
+ onEdit: () => null,
+};
+
+export default PostViewer;

Now, tie this all together in src/App.js. You can create a “New Post” button to create a new post, and make it so that you can edit any other existing post as well:
import React, { Component } from ‘react’;
import { Button, Container } from ‘reactstrap’;

import PostViewer from ‘./PostViewer’;
import PostEditor from ‘./PostEditor’;

class App extends Component {
state = {
editing: null,
};

render() {
const { editing } = this.state;

return (
<Container fluid>
<Button
className="my-2"
color="primary"
onClick={() => this.setState({ editing: {} })}
>
New Post
</Button>
<PostViewer
canEdit={() => true}
onEdit={(post) => this.setState({ editing: post })}
/>
{editing && (
<PostEditor
post={editing}
onClose={() => this.setState({ editing: null })}
/>
)}
</Container>
);
}
}

export default App;

Add User Authentication to the React + GraphQL Web App
One simple way to add authentication to your project is with Okta. 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. 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}

You’re also going to need an API token later for the server, so while you’re in there, navigate to API -> Tokens, then click on Create Token. You can have many tokens, so just give this one a name that reminds you what it’s for, like “GraphQL Express”. You’ll be given a token that you can only see right now. If you lose the token, you’ll have to create another one. Add this to .env also.
REACT_APP_OKTA_TOKEN={yourOktaAPIToken}

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.
yarn add @okta/okta-react@1.1.1 react-router-dom@4.3.1

In order to know if the user is authenticated, Okta requires the app to be wrapped in a Security component with some configuration. It also depends on React Router, so you’ll end up with a BrowserRouter component, wrapping a Security component, wrapping an ApolloProvider component, which finally wraps your App in a Route. Your src/index.js file should end up looking like this:
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import { BrowserRouter, Route } from ‘react-router-dom’;
import { Security, ImplicitCallback } from ‘@okta/okta-react’;
import { ApolloProvider } from ‘react-apollo’;

import ‘bootstrap/dist/css/bootstrap.min.css’;
import App from ‘./App’;
import registerServiceWorker from ‘./registerServiceWorker’;
import client from ‘./apollo’;

ReactDOM.render(
<BrowserRouter>
<Security
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}
>
<ApolloProvider client={client}>
<Route path="/implicit/callback" component={ImplicitCallback} />
<Route path="/" component={App} />
</ApolloProvider>
</Security>
</BrowserRouter>,
document.getElementById(‘root’)
);
registerServiceWorker();
if (module.hot) module.hot.accept();

The Okta SDK comes with a withAuth higher order component (HoC) that can be used for a wide variety of auth-related things, but for this example, you’ll only need to know whether or not you’re authenticated, and some information about the user. To make this a little easier, I wrote a simple HoC to override the one that comes with the Okta SDK. Create a new file src/withAuth.js containing the following:
The post Build a Simple Web App with Express, React and GraphQL appeared first on SitePoint.

Link: https://developer.okta.com/blog/2018/10/11/build-simple-web-app-with-express-react-graphql

Do You Need to Know React as a WordPress Developer?

This article on whether you need to know React as a WordPress developer was originally published by Torque Magazine, and is reproduced here with permission.
The new WordPress content editing system Gutenberg will be powering the WordPress post editor in WordPress 5.0. Gutenberg is a “block-based” editor. When creating content, everything is a block. If you have a post that is one paragraph, one header, and then two paragraphs, that’s four blocks.
Gutenberg comes with a set of default “core” blocks — paragraph, header, recent posts, image, blockquote, etc. If you’re using Gutenberg to create content, you use those blocks or custom blocks that are provided by WordPress plugins you install on your site.
Gutenberg is a JavaScript-driven interface. Specifically, it is built using Facebook’s open-source user interface library “React”. This post explains a little bit about creating your own custom blocks for use in the Gutenberg editor using JavaScript. You do not have to use JavaScript to create blocks. Advanced Custom Fields (ACF) recently announced a neat looking system for creating custom blocks with PHP.
What Is React?
In front-end development, the least performant things you do are reading and writing from the DOM. A very hard thing to do, consistently across browsers, is referencing and updating the DOM. React provides a better system for this, by implementing a reactive programming model and a virtual DOM abstraction.
Instead of interacting with the DOM directly, for example using jQuery.html() or jQuery.val(), React creates a virtual representation of the DOM. We call this a virtual DOM or VDOM. The VDOM is a JavaScript object that represents the structure of the DOM. Whenever your React code communicates to React a change in any of the data, the VDOM is recalculated. After that React calculates the difference between the DOM as it existed before the change and after the change. Then React (really ReactDOM or React Native) updates just the parts of the DOM that needs changed. How it does this doesn’t matter really.
How Is React Being Used in Gutenberg?
React is a library for creating reusable components. Because they are reusable, we can compose interfaces out of components. It is an open-source project created at Facebook.

Everything is a block. Text, images, galleries, widgets, shortcodes, and even chunks of custom HTML, no matter if it’s added by plugins or otherwise. You should only have to learn to master a single interface: the block interface, and then you know how to do everything. – Gutenberg Handbook

Blocks are the basic unit of Gutenberg. We compose content out of one or more blocks.
Components are the atomic unit of React, we compose React apps out of components. Gutenberg is created with React, so each block is composed of one or more components.
It’s important to note, and I’ll cover this more in this series of posts, but Gutenberg adds a thin abstraction layer over React. In our Gutenberg code, we’ll use wp.createElement instead of React.createElement. It works the same, but when React’s API changes, WordPress can decide when to support those changes and provide a backward-compatibility wrapper or decided not to.
This is good planning for the future, but for now, it’s just React.
The post Do You Need to Know React as a WordPress Developer? appeared first on SitePoint.

Link: https://www.sitepoint.com/do-you-need-to-know-react-as-a-wordpress-developer/

Using Recompose to Share Functionality Between React Components

Sharing functionality between React components is a pretty common need. The concept is that we can establish the behavior in one place and then extend it across different components. Higher-Order Components are one way to do this. Yet, there is another way using a library called Recompose.

GitHub Repo
What is Recompose?
The documentation helps us answer that:
Recompose is a React utility belt for function components and higher-order components. Think of it like lodash for React.
Basically, it’s a …
The post Using Recompose to Share Functionality Between React Components appeared first on CSS-Tricks.

Link: https://css-tricks.com/using-recompose-to-share-functionality-between-react-components/

Techniques for Animating on the Canvas in React

I recently experimented with audio visualization in React on the Twilio blog. While I meant to teach myself more about the web audio API I found that I picked up a few techniques for animating in canvas within a React project. If you’re creating a canvas animation in React then perhaps this will help you too.
Good References
First up, if you’ve used React before you’ll know that you’re supposed to avoid touching the DOM and let React handle it. If you’ve worked with an HTML5 before, you’ll also know that to get a context with which to draw on the canvas, you need to call directly on the canvas element itself. Thankfully this is an edge case that React supports through refs.

Link: https://dzone.com/articles/techniques-for-animating-on-the-canvas-in-react

Developer Tips: Creating a Hybrid Restaurant Application Using React

While working with complex applications with an infinite number of requirements, developers have to face lots of unforeseen challenges. Am I doing this right, because this doesn’t look right? We’ve all been at that stage of app development, haven’t we?
Hybrid applications built using React for the web and React Native for mobile are becoming popular. Can I build complex applications using this stack? Is investing time in React worth it? What do you do if you come across an undocumented bug that doesn’t have a ready fix? Here, we go over these and similar scenarios as we attempt to build a front-end application for a restaurant.

Link: https://dzone.com/articles/developer-tips-creating-a-hybrid-restaurant-applic?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

How to Build React 16 Web Apps with the Sencha Grid

React 16 is the first version of React built on top of React’s new core architecture, codenamed “Fiber". React 16 is designed from the ground up to support asynchronous rendering, which allows processing large component trees without blocking the main execution thread. It supports a number of key features such as catching exceptions using error boundaries, returning multiple components from render, reduced file size and support for MIT license.
If you’re developing a data-driven web application with React 16, chances are you’ll use a grid or spreadsheet-like interface at some point to display data for your users. Depending on the context, your users may expect the grid in your application to be capable of:

Scrolling with a fixed header
Sorting by clicking on a column header
Showing and hiding specific columns
Paging, grouping, and summarization
Editing data in cells
Exporting to Excel
Drilling down/row expansion

A grid can be one of the trickiest and most complex UI components to build in React because many of the necessary features require both significant React expertise, as well as the willingness and ability to dig down into the DOM. Fortunately, the ExtReact Grid provides all of these capabilities and more.
In this article, we’re going to create an example using the Sencha ExtReact Grid that shows information about Stocks and equities companies. If you want to code a grid using an HTML table or another third-party component, you might have to do something like handle clicking on a column header to sort, or clicking on a divider between a column header to resize, or maybe sliding a pager and doing a fetch for the next page of data. With ExtReact Grid, these functionalities are built in. Want to try it yourself? Get started with a 30-day free trial of ExtReact today — sign up here.
Let’s get started with building an application using ExtReact Grid.
Getting Started with ExtReact App Generation
To get started on developing a React application with ExtReact components, please follow the steps below:
Make sure you have a Node environment set up
First, make sure you have Node 8.11+ and NPM 6+ set up on your system. You can download the latest Node version from the Node web site. If you’ve already installed Node, you can easily check the node and npm versions by using these commands:
node -v
npm -v

Get your login credentials for the ExtReact npm repo
ExtReact npm packages are hosted on Sencha’s private npm repo. You log in to that repo once to get access to all ExtReact packages. To get login credentials, go to the ExtReact 30-Day Free Trial page and fill out the form. We’ll send you an email with login details as well as some links to resources such as the docs and sample projects.
Login to ExtReact npm repo and get ExtReact app generator
The next step is to log in to Sencha’s private npm repo, which hosts the ExtReact packages. Use your npm login (provided in the email) to associate the repo with the @sencha scope, and enter the credentials when prompted:
npm login — registry=http://npm.sencha.com — scope=@sencha

The next step is to install ExtReact generator package.
npm install -g @sencha/ext-react-gen

Create your first React App
Run the Yeoman generator to create your first ExtReact app:
ext-react-gen app your-app-name-here -i

The generator will ask you to name your app, name the npm package, and select a theme. The default Material theme (based on Google’s Material design guidelines) is a good choice as a starting theme. Select "Generate an Empty App". The generator will also prompt you to create a new directory for your project. The generator will then download and create your sample application, including relevant dependencies.
Run your React App
In the generator output, you will find steps to run your application. It’s as simple as changing to your new application directory and running the application using:
npm start

This will fire up the app, your empty React app will just show up with the title of the app. The main component (e.g. StocksGrid) in the application has one container at the root, which is marked as full screen, layout is set to fit, which means it will stretch its child to fill it.
See the code up to this step on GitHub.
Adding a Grid to the application
Add Stocks Data
We’ll be adding an example data set, called stocks.json to the application. It’s a fairly large data set, around 10,000 rows in json, and each row represents a company or ticker symbol — so we have the name of the company, ticker symbol, sector, industries they are in, and an array of ticks which are the last 5 sales of that stock. This is the data we’re going to display in our grid. In a real-world application, all of this data would be returned on the back-end. We’re going to load it statically for this sample application rather than go through all of the mechanics of how to build a back-end rest API. But it’s going to be loaded in the exact same way you would fetch from a real back-end.
Creating a Basic Grid
In the StockGrid component render method, we’re going to return a grid with columns.
To put columns in our grid, we use a column component, and it takes a data index that is the same as the name field of the stocks data. It takes a text prop that is the column header text, and then we can also give the column a width, like a fixed width or a flex or a combination of flex and minimum or maximum as well. We’ll add column components for company name, symbol, ticks, sector, and industry. Create a new StocksGrid class with Grid as shown below:

<Column dataIndex="name" text="Name" width={300} />
<Column dataIndex="symbol" text="Symbol" />
<Column dataIndex="ticks" text="Trend" />
<Column dataIndex="sector" text="Sector" width={200} />
<Column dataIndex="industry" text="Industry" width={350} />
</Grid>

Now, add StockGrid to Class App as shown below:
export default class App extends Component {
render() {
return (
<ExtReact>
<StocksGrid />
</ExtReact>
)
}
}

See the code up to this step on GitHub.You will be able to see the web application with empty Grid on npm start.
Binding Stock Data with Grid
A grid in ExtReact is a data table that pulls in and renders data from an Ext Data Store. In ExtReact, our store implementation is a data structure that allows you to sort and filter data for a grid or components (like lists or charts).
We can now start by loading the stocks data and creating a store. Again, grids always grab their data from the store, and some of the interactions with grid will trigger events on the store, like reloading or sorting or paging. So to do that, we’ll create our store here.
The Ext data store is different from the flux store. What makes the grid and the store a little different from the standard React approach is that the two are tightly integrated. Typically, you can pass data directly to a store, or a store can pull data on its own from a back-end using a proxy. With ExtReact Grid, you get interactive functionality like filtering, sorting, paging, grouping, and summarization without having to actually code it.
For this example, we’re passing the data directly to the store from the Stocks data file. You can also create a store with a proxy config — having a proxy allows us to do all sorts of great things like remote paging, filtering, and sorting. We set autoload to true, so it automatically loads the grid. The data isn’t particularly sorted by any criteria, so we’re going to have it sort on the client-side by specifying the name property.
this.store = new Ext.data.Store({
data: stocks,
autoLoad: true,
sorters: [{
property: ‘name’
}],
listeners: {
update: this.onRecordUpdated
}
})

In the Grid, assign the store config to the store that was created.
<Grid store={this.store}>

</Grid>

Now, we have a grid with all the data as shown below:

With this simple code, you get a lot of features for free — such as sorting — which allows you to click on any column header and it automatically sorts (see the symbol column in the example below).
In this case, the sorting is done on the client side. But if we implemented a real back-end API, we could configure the proxy to do remote sorting on the back-end and use an "order by clause" in the database to do a sort.
You also get resizable columns for free. So even though we set a width on these columns, if the user wants to see something or close something, he can do that by dragging the column from side to side.
You also get a nice grouping feature too. So if we wanted to group by industry, we could say group by this field, and it will group all of the data by the value of industry, and it will give you a pinned header as you scroll down for each of the groupings.

You’ll notice that this data is rendering pretty quickly for 10,000 records. The reason it renders so quickly is because it’s using what we call buffered rendering. So despite the fact that this table looks full, and you can scroll down and it keeps going and going, on initial loading it only renders a little bit more than what you’re actually seeing in terms of the "view port height."
The post How to Build React 16 Web Apps with the Sencha Grid appeared first on SitePoint.

Link: https://www.sitepoint.com/how-to-build-react-16-web-apps-with-the-sencha-grid/

Building Chatbots in React With Botonic

My work with chatbots fluctuates when I get time to work on my two main ideas: generative fiction and a bot for documentation. You create most bots with a server-side language that returns JSON to an endpoint and renders to an audio or visual interface. This means that while all bot platforms have their own APIs and SDKs, there are a plethora of tools to help you write once and deliver to multiple platforms. The good folks at Botonic got in touch and asked for feedback on the developer experience for their platform that lets you create bots using React for a variety of chat and voice interfaces.
Getting Started
I’m pleased to say that Botonic has a great getting started experience, with text and video documentation. Start by installing the npm module:

Link: https://dzone.com/articles/building-chatbots-in-react-with-botonic?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev