Gatsby Posts
How to Connect Gatsby to WordPressGatsby
How to Connect Gatsby to WordPressGatsby
Gatsby is a blazing-fast website framework for React. It allows developers to build React-based websites within minutes.
WordPress
WordPress is a free and open-source content management system written in PHP and paired with a MySQL or MariaDB database. Features include a plugin architecture and a template system, referred to within WordPress as Themes.
Integrate Gatsby with WordPress
Install gatsby-source-wordpress package
npm install gatsby-source-wordpress
gatsby-config.js file
add the gatsby config file in the following code
plugins: [
...
{
resolve: `gatsby-source-wordpress`,
options: {
// Specify the URL of the WordPress source
baseUrl: `localhost:8888/wordpress`,
protocol: `http`,
// Indicates if a site is hosted on WordPress.com
hostingWPCOM: false,
// Specify which URL structures to fetch
includedRoutes: [
'**/posts',
'**/tags',
'**/categories'
]
}
}
Now connect your gatsby website and Wordpress.
Here is an example of the GraphQL API query
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
export default ({ data }) => {
return (
{data.allWordpressPost.edges.map(({ node }) => (
<div>
<p>{node.title}</p>
</div>
))}
)
}
export const pageQuery = graphql`
query {
allWordpressPost(sort: { fields: [date] }) {
edges {
node {
title
excerpt
}
}
}
}
Hope this helps.
Why developer choose React JSReact
Why developer choose React JSReact
There are a few reasons why developers choose ReactJS and they are :-
- JavaScript XML or JSX
- React use Virtual DOM
- ReactJs Props
- One-Way Data Binding
- Quick Rendering
- SEO Friendly
- Helpful Developer Toolset
JavaScript XML or JSX
It is a markup syntax that describes the appearance of the application's interface. It creates the same syntax as HTML and is used by developers to create feedback elements.
JSX is one of the best features of React JS as it makes it very easy for developers to write building blocks.
React use Virtual DOM
This feature helps speed up the app development process. The algorithm allows the web page to be copied into React's virtual memory.
The original DOM there is represented by a virtual DOM.
ReactJs Props
ReactJS Props allows developers to move custom development data into its specific UI components. This helps in rendering JavaScript components and improving the UI development experience.
One-Way Data Binding
Feedback uses a stream of data that is directionless, forcing developers to use the callback feature to edit components and prevent them from editing directly.
Control of data flow from a single point is achieved with a JS app architecture component called Flux. It really gives developers better control over the application and makes it more flexible and effective.
Quick Rendering
This means that a small edit made at the top level can hit the app UI hard. Thanks to the virtual DOM, it can be tested first to determine the risk level with each change before finalizing all changes.
SEO Friendly
To make any application work well, it is important that the search engine selects it; Two factors are important for applications: fast load time and rendering. If both of these boxes are ticked, your app will rank higher on Google results pages.
React's super-fast rendering feature drastically reduces page load time, enabling businesses to rank their apps on the first page of Google search.
Helpful Developer Toolset
Facebook has included many developer tools in the React JS framework for React and Chrome, and they greatly help developers find parents and child components, observe their hierarchies, and test their current status.
Through self-learning, developers will be able to use emerging technologies in real, live, projects.
So, developers choose ReactJS hope this help.
Best practices for React JS developer part-2React
Best practices for React JS developer part-2React
In the previous article, we learned 5 areas or tips on Best practices for React JS developer.
In this article, we will learn more about areas or tips
- Object Destructuring.
- When pass value in props
- Tags close it self.
- Do not use underscore in any method name.
- Use alt in img tag.
Object distracting
You can use object distracting
Not Good
return (
<>
{user.firstName}
</>
)
Good
const { firstName } = user;
return (
<>
{firstName}
</>
)
When pass value in props
When pass the data between two component that time use camelCase for prop names.
Not Good
<Home
UserName="demo"
phone_number={9898989898}
/>
Good
<Home
userName="demo"
phoneNumber={9898989898}
/>
Tags close it self
Any component in not use children so closing it self
Not Good
<Home userName="demo"></Home>
Good
<Home
userName="demo"
/>
Do not use underscore in any method name
You don't need underscores in any React method.
Not Good
const _onClickHandler = () => {
// Your code
}
Good
const onClickHandler = () => {
// Your code
}
Use alt attribute in img tag
Do use alt attribute in the img tag. and don’t use picture or image name in your alt property.
Not Good
<img src="hello.png" />
Good
<img src="hello.png" alt="This is hero image" />
Best practices for React JS developerReact
Best practices for React JS developerReact
Today we are going to see best practices for React JS developer
- Passing a boolean variables.
- Do not define a function within a render
- Naming of the components
- Use of the Ternary Operators
- Don’t Need Curly Braces in string
Passing a boolean variables
Passing boolean variables in to two components.
Not Good
return (
<Home showTitle={true}/>
);
Good
return (
<Home showTitle/>
);
Do not define a function within a render
Don’t define a function inside render.
Not Good
return (
<button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>
Example
</button>
)
Good
const submitData = () => dispatch(ACTION_TO_SEND_DATA)
return (
<button onClick={submitData}>
Example
</button>
)
Naming of the components
You can use PascalCase for name of the components and camelCase for name of the instances.
Not Good
import createCard from './CreateCard';
const ReservationItem = <ReservationCard />;
Good
import CreateCard from './CreateCard';
const reservationItem = <ReservationCard />;
Use of the Ternary Operators
Developer how can use ternary operator in React js.
Not Good
const { role } = user;
if(role === 'ADMIN') {
return <AdminUser />
}else{
return <NormalUser />
}
Good
const { role } = user;
return role === 'ADMIN' ? <AdminUser /> : <NormalUser />
Don’t Need Curly Braces in string
When developer passing string props to a children component
Not Good
return(
<Navbar title={"My Special App"} />
)
Good
return(
<Navbar title="My Special App" />
)
Hope this helps for React js developer
How to connect contentful CMS in the gatsby websiteGatsby
How to connect contentful CMS in the gatsby websiteGatsby
Gatsby
Gatsby is a blazing-fast website framework for React. It allows developers to build React-based websites within minutes.
Contentful CMS
Contentful is content infrastructure. Contentful lets you create, manage and distribute content to any platform. Unlike a CMS, Contentful give you total freedom to create your own content model so you can decide which content you want to manage.
Integrate Gatsby with Contentful
Install gatsby-source-contentful package
npm install gatsby-source-contentful
gatsby-config.js file
add the gatsby config file in the following code
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: `your_space_id`,
accessToken: `your_access_token`
}
}
]
Now connect your gatsby website and contentful CMS.
Here is an example of the GraphQL API query
import React from "react"
import { useStaticQuery, graphql, Link } from "gatsby"
import Layout from "../components/layout"
const Blog = () => {
const data = useStaticQuery(
graphql`
query {
allContentfulBlogPost{ //BlogPost collection name
edges {
node {
title
id
slug
}
}
}
}
`
)
return (
<div>
<p>
<Link to="/">Go back to the homepage</Link>
</p>
<ul className="posts">
{data.allContentfulBlogPost.edges.map(edge => {
return (
<li className="post" key={edge.node.id}>
<h2>
<Link to={`/blog/${edge.node.slug}/`}>{edge.node.title}</Link>
</h2>
<p className="excerpt">
{edge.node.excerpt.childMarkdownRemark.excerpt}
</p>
<div className="button">
<Link to={`/blog/${edge.node.slug}/`}>Read More</Link>
</div>
</li>
)
})}
</ul>
</div>
)
}
export default Blog
Hope this helps.
How to connect strapi CMS in gatsby websiteJavascript
How to connect strapi CMS in gatsby websiteJavascript
Gatsby
Gatsby is a blazing-fast website framework for React. It allows developers to build React-based websites within minutes.
Strapi CMS
Strapi is an open-source, Node.js based, Headless CMS that saves developers a lot of development time while giving them the freedom to use their favorite tools and frameworks.
Integrate Gatsby with Strapi
Install gatsby-source-strapi package
npm i gatsby-source-strapi
gatsby-config.js file
- add the gatsby config file in the following code
plugins: [
{
resolve: `gatsby-source-strapi`,
options: {
apiURL: "your strapi server",
contentTypes: ["restaurant"], //add your collections name
queryLimit: 1000,
}
}
]
Now connect your gatsby website and strapi CMS
- Here is an example of the GraphQL API query
import { StaticQuery, graphql } from 'gatsby';
const query = graphql`
query {
allStrapiRestaurant {
edges {
node {
strapiId
name
description
}
}
}
}
`
const IndexPage = () => (
<StaticQuery
query={query}
render={data => (
<ul>
{data.allStrapiRestaurant.edges.map(restaurant => (
<li key={restaurant.node.strapiId}>{restaurant.node.name}</li>
))}
</ul>
)}
/>
);
export default IndexPage;
Hope this helps.
How to make a Progressive Web AppGatsby
How to make a Progressive Web AppGatsby
What is a PWA?
A Progressive Web App (PWA) is a hybrid of a regular web page and a mobile application. A PWA combines features offered by most modern browsers with the benefits of the mobile experience. They are built using standard web technologies, including HTML, CSS, and JavaScript. The functionalities include working offline, push notifications, and device hardware access and enabling creating user experiences similar to native applications.
How to make a PWA
Following Below steps
- Create an app manifest.json file
- Add it to your base HTML template
- Create the
service worker
- Serve the service worker on the root of the scope you used in the manifest
- Add a block to your base HTML template file
- Site deploy in your server
Create an App Manifest
- Add the following information in 'manifest.json'
{
name: `Name`,
short_name: `Sort name`,
start_url: `/`,
display: `standalone`,
icon: `Favicon icon`,
icons: [
{
"src": "icon by size",
"sizes": "144x144",
"type": "image/png",
"purpose": "any"
},
{
"src": "icon by size",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icon by size",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
theme_color: `Theme color`,
background_color: `Background color`,
]
}
- Manifest.json file in add this type of code including name, short_name, start_url, display, icon, icons, theme_color, background_color.
Add the Manifest to Your Base HTML Template
- Add the following line in yore 'index' file
Create offline.html as an Alias to index.html
By default, the service worker code below will render /offline.html instead of any resource it can't fetch while offline. Create a file at
Create a Service Worker
- Create one file in yore root (sw.js)
- Link the sw.js file in the body tag
We have created some pages like
- Home page (/)
- Blog page (/blog)
- Contact information (/contact)
- Resume (/resume)
- offline.html
- Add the code in your sw.js file
self.addEventListener("install", function(event) {
event.waitUntil(preLoad());
});
var preLoad = function(){
return caches.open("offline").then(function(cache) {
return cache.addAll(["/blog/", "/blog", "/", "/contact",
"/resume", "/offline.html"]);
});
};
self.addEventListener("fetch", function(event) { event.respondWith(checkResponse(event.request).catch(function()
{
return returnFromCache(event.request);
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};
var addToCache = function(request){
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
var returnFromCache = function(request){
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match("offline.html");
} else {
return matching;
}
});
});
};
- Servicer worker file add your body tag
load the service worker file in
<script>
if (!navigator.serviceWorker.controller) {
navigator.serviceWorker.register("/sw.js").then(function(reg) {
console.log("Service worker has been registered for scope: " + reg.scope);
});
}
</script>
Last step
- Deploy code in yore live site
- Create lighthouse report and check PWA
How to load dynamic blog in Gatsby SiteGatsby
How to load dynamic blog in Gatsby SiteGatsby
We have recently developed a site into the gatsby.
We have a blog site and hosted it on a different domain but now we want to move to one place at our main site. now, we have challenges for displaying dynamic blogs on the gatsby site.
Finally, I found that gatsby provides support to render dynamic blogs as static pages. when build is created that time fetches the blogs from the server and creates a static page for all the blogs.
Gatsby is a very good platform and manages such a kind of thing easily.
So, I will show you how to create static pages from the API response into the Gatsby site.
Here are the steps you need to follow correctly.
Steps 1
Create a one blog file where you want to load a blog in your design.
For an ex. I created a file blog/index.js
inside the component directory and the code looks like this,
Steps 2
Open a file gatsby-node.js
Declare the const for the API URL at the beginning of the file.
const blogURL = 'http://blog-api.com/api/posts';
We need to create an instance of the node-fetch
for fetching data from the API server.
const fetch = require(`node-fetch`);
Import the path for resolving the page while creating a static page.
const path = require('path');
See the example how to create a static page from APIs. code look's like,
exports.createPages = (async ({graphql, actions}) => {
const blogs = await fetch(blogURL);
blogs.data.forEach((blog) => {
createPage({
path: 'blog/' + blog.slug,
component: path.resolve(`./src/components/blog/index.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: blog.slug,
blog: blog,
},
})
})
Now we are done, and you can access the blog page via slug.