Categories
Article birthday

The Thirteenth Fourth

Well boy howdy. The 13th birthday of CSS-Tricks has rolled around. A proper teenager now, howabouthat? I always take the opportunity to do a bit of a state of the union address at this time, so let’s get to it!

Design

Technically, we’re still on v17 of the site design. This was the first design that I hired first-class help to do, and I’m still loving it, so I haven’t had much of an itch to do massive changes to it. Although it is quite different¹ today than it was on launch day.

For example…

Maybe next year we’ll do something different again. My list is starting to grow for some behind-the-scenes tech stuff I wanna re-jigger, and sometimes that goes hand in hand with redesign work.

Closed Forums

The forums on this site have been a mental weight on me for literally years. Earlier this year I finally turned them off. They are still there, and probably always will be (so the URLs are maintained), but nobody can post new threads or replies.

It was a painful move. Even as I did it, there was still some regular daily activity there and I’m sure it didn’t feel good to those people to have a place they have invested time in shut down. Here’s why I did it:

  • Nobody here, including me, checked in on the forums with any regularity. Unmoderated public forums on the internet are not acceptable to me.
  • The spam volume was going up. There were periods where most posts, even after the automatic spam blocking I get from Akismet, where spam that required manual removal. Even if we had a dedicated forums employee, that’s no fun, and since we didn’t, it was just a random job for me and I don’t need a time sink like that.
  • The forums represent a certain level of technical debt. They need to be updated. Their design needs to be functional in the context of this site. At one point I ripped out all custom styles and left it be the default theme, which was a good step toward reducing technical debt, but in the end it wasn’t enough.

I can handle some work and some technical debt, of course. But when you combine those things with the fact that the forums don’t contribute much to what I consider to be the success of the site. They don’t exactly drive page views or advertising demand. There isn’t really money to hire help specifically for the forums. But that’s a small part of it. I want this site to help people. I think we can do that best if we focus on publishing with as little divided attention as possible. I think there are places on the internet that are better for forum-like discourse.

Now that they’ve been off a number of months, I can report that the lifting of the mental weight feels very good to me and there is been little if any major negatives.

Social

Here’s another mental weight I lifted: I stopped hand-managing the Twitter account (@css). I still think it’s good that we have a Twitter account (and that we have that cool handle), but I just don’t spend any time on it directly like I used to.

In the past, I’d queue up special articles with commentary and graphics and stuff and make sure the days were full with a spread of what I thought would be interesting tweets about web design and development. That’s fine and all, but it began to feel like a job without a paycheck.

We don’t get (or seem to drive) a lot of traffic from Twitter. Google Analytics shows social media accounts for less than 1% of our traffic. Investing time in “growing” Twitter just doesn’t have enough of an upside for me. Not to mention the obvious: Twitter can be terribly toxic and mentally draining.

So now, all our posts to Twitter are automated through the Jetpack social media connection (we really use Jetpack for tons of stuff). We hit publish on the site and the article is auto-tweeted. So if you use Twitter like an RSS feed of sorts (just show me the news!), you got it.

The result? Our follower count goes up at the same rate it always did. Engagement there is the same, or higher, than it ever was. What a relief. Do ten times less work for the same benefit.

When I have the urge to share a link with commentary I use the same system we’ve always had here: I write it up as a link blog post instead. Now we’re getting even more benefit: long-term content building, which is good for the thing that we actually have on our side: SEO.

Someday we could improve things by hand-writing the auto-tweet text with a bit more joie de vivre, crediting the author more clearly, and, #stretchgoal, a custom or fancy-generated social media graphic.

Opened Up Design Possibilities

One aspect of this site that I’ve been happy with is the opportunity to do custom design on content. Here are some examples of that infrastructure.

On any given blog post, we can pick a template. Some of those templates are very specific. For example, my essay The Great Divide is a template all to itself.

In the code base, I have a PHP template and a CSS file that are entirely dedicated to that post. I think that’s a fine way to handle a post you want to give extra attention to, although the existence of those two files is a bit of technical debt.

I learned something in the creation of that particular essay: what I really need to open up the art direction/design possibility on a post is a simple, stripped-down template to start from. So that’s what we call a “Fancy Post” now, another template choice for any particular post. Fancy Posts have a hero image and a centered column for the content of the post. From there, we can use custom CSS to style things right within WordPress itself.

For example, my recent post on DX is styled as a Fancy Post with Custom CSS applied right within the block editor.

The Block Editor itself is a huge deal for us. That was one of my goals for the year, and we’ve really exceeded how far we’d get with it. I think writing and editing posts in the block editor is a million miles ahead of the old editor.

The hardest challenge was (and still is really) getting the block transforms set up for legacy content. But once you have the power to build and customize blocks, that alone opens up a ton of design possibility within posts that is too big of a pain in the butt and too heavy on technical debt otherwise.

Another door we opened for design possibilities is a classic one: using categories. A sort of freebie you get in WordPress is the ability to create templates for all sorts of things that just sort of automatically work if they are named correctly. So for example I have a filed called category-2019-end-of-year-thoughts.php and that fully gives me control over making landing pages for groups of posts, like our end-of-year thoughts homepage. Not to mention our “Guide Collection” pages which are another way to programmatically build collections of pages.

That’s a lot of tools to do custom work with, and I’m really happy with that. It feels like we’ve given ourselves lots of potential with these tools, and only started taking advantage of it.

Speaking of which, another aspect of custom design we have available is the new book format…

eCommerce

We’re using WooCommerce here on the site now again. I just got done singing the praises of the Block Editor and how useful that is been… WooCommerce is in the same boat. I feel like I’m getting all this powerful functionality with very little effort, at a low cost, and with little technical debt. It makes me very happy to have this site on WordPress and using so much of suite of functionality that offers.

So for one thing, I can sell products with it, and we have products now! Lynn Fisher designed a poster for our CSS Flexbox guide and designed a poster for our CSS Grid guide, which you can now buy and ship anywhere in the world for $25 each. Look, with the Block Editor I can put a block for a poster right here in this post:

Another thing we’re using WooCommerce for is to sell our new book, The Greatest CSS Tricks Vol. I. If we actually made it into a proper eBook format, WooCommerce could absolutely deliver those files digitally to you, but we haven’t done that yet. We’ve take another path, which is publishing the book as chapters here on the site behind a membership paywall we’re calling MVP supporters. The book is just one of the benefits of that.

WooCommerce helps:

  • Build a membership system and sell memberships. Membership can lock certain pages to members-only as has programmatic hooks I can use for things like removing ads.
  • Sell subscriptions to those memberships, with recurring billing.
  • Sell one-off products

And I’m just scratching the surface of course. WooCommerce can do anything eCommerce wise.

Analytics

They are fine. Ha! That’s how much I worry about our general site analytics. I like to check in on them from time to time to make sure we’re not tanking or anything scary, but we never are (knock on wood). We’re in the vicinity of 8m page views a month, and year-over-year traffic is a bit of a dance.

Sponsors

THANK YOU THANK YOU THANK YOU

That’s what I have to say to all our sponsors. We’re so damn lucky to work with a lineup of sponsors that I wholeheartedly endorse as well as literally use their products. We have different sponsors all the time, but these are the biggest and those who have been with us the longest.

  • Automattic: Thanks for building great software for the WordPress ecosystem. This site is made possible by a heaping helping of that software.
  • Netlify: Thanks for bringing the Jamstack world to life. I’m also a big fan of this way of building websites, and think that Jamstack should be the foundation for most websites. Beyond that, you’ve redefined modern developer experience.
  • Flywheel: Thank you for hosting this website, being a high-quality host I can trust and who has been helpful to me countless times. This is what high-quality WordPress hosting looks like.
  • Frontend Masters: Thank you for being an education partner that does things right and helps me have the best possible answer for people when they are searching a more structured formal education about doing web work: go try Frontend Masters.

If you’re trying to reach front-end developers with your products, that’s literally how I make a living and can help.

My Other Projects

CodePen is no spring chicken either, being over 8 years old itself. I repeat myself a lot with this particular aspect of talking about CodePen: we’ve got a ton of ideas, a ton of work to do, and we can’t wait to show you the CodePen of tomorrow. 2020 for CodePen has been a lot different than the last 2-3 years of CodePen. Some technical choices we’ve made have been starting to pay off. The team is vibing very well and absolutely tearing through work faster than I would have thought possible a few years ago, and we haven’t even unlocked some of the biggest doors yet. I know that’s vague, but we talk in more detail about stuff on CodePen Radio.

ShopTalk, as ever, is going strong. That’s 420 episodes this week, friends. Dave has me convinced that our format as it is, is good. We aren’t an instruction manual. You don’t listen to any particular episode because we’re going to teach you some specific subject that we’ve explicitly listed out. It’s more like water cooler talk between real world developers who develop totally different things in totally different situations, but agree on more than we disagree. We might evolve what ShopTalk show is over time, but this format will live on because there is value in discussion in this format.

Life

My wife Miranda and I are still in Bend, Oregon and our Daughter Ruby is two and a half. She’s taking a nap and I’m looking at the monitor as I type.

We have the virus here like everywhere else. It’s sad to think that we’re this far into it and our local hospital is pleading with people to be careful this holiday weekend because they are very near capacity and can’t take much more. Here’s hoping we can get past this painful period. Stay safe and stay cool, friends, thanks for reading.


  1. I always feel bad when I make design changes away from an actual professional designer’s work. Is the site design better today than Kylie’s original? Uhm probably not (sorry for wrecking it Kylie!), but sometimes I just have an itch to fiddle with things and give things a fresh look. But the biggest driver of change is the evolving needs of the site and my desire to manage things with as little technical debt as possible, and sometimes simplifying design things helps me get there.

The post The Thirteenth Fourth appeared first on CSS-Tricks.

Source: css tricks

Categories
plugins WordPress

Beginner’s Guide to WordPress Plugin Development

The WordPress CMS has changed the face of our Internet and allowed a surge of new ideas to prosper, and its open-source movement holds a strong presence rooted in software and web development….

Visit hongkiat.com for full content.
Source: hongkiat

Categories
Article aspect ratio responsive images

Fluid Images in a Variable Proportion Layout

Creating fluid images when they stand alone in a layout is easy enough nowadays. However, with more sophisticated interfaces we often have to place images inside responsive elements, like this card:

Screenshot. A horizontal card element with an image of two strawberries against a light blue background to the left of text that contains a heading and two sentences.

For now, let’s say this image is not semantic content, but only decoration. That’s a good use for background-image. And because in this context the image contains an object, we can’t allow any parts to be cropped out when it’s responsive, so we’d pick background-size: contain.

Here’s where it starts to get tricky: on mobile devices, this card shifts direction and becomes vertical, with the image on top. We can make that happen with any sort of CSS layout technique, and probably best handled with CSS grid or flexbox.

Screenshot. The same strawberry card but in a vertical format.

But as we test for smaller screens, because of the contain property, this is what we get:

The same card element in vertical but now the strawberry image is not flush with the top border of the card.
Hey, get back up there!

That’s not very nice. The image resizes to maintain its aspect ratio without cutting off any details, and if the image is important content and should not be cropped, we can’t change background-size to cover.

At this point, our next attempt might be familiar to you: placing the image inline, instead the background. 

On desktop, this works fine:

It’s not bad on mobile either:

But on smaller screens, because of all the fixed sizes, the image’s proportions get distorted.

Screenshot. The vertical card element with the strawberry image out of proportion, causing the strawberries to appear stretched vertically.
Hmm, those strawberries are not as appetizing when stretched.

We could spend hours fiddling with the image, the card, the flex properties, going back and forth. Or, we could…

Separate main content from the background

This is the base for obtaining much more flexibility and resilience when it comes to responsive images. It might not be possible 100% of the time but, in many cases, it can be achieved with a little effort on the design side of things, especially if this approach is planned beforehand.

For our next iteration, we’re placing our strawberries image on a transparent background and setting what was the blue color in the raster image with CSS instead. Go ahead and play with viewport sizes in this demo by adjusting the size of the sample space!

CodePen Embed Fallback

Looking deeper at the styles, notice that we’ve also added padding to the div that holds the image, so the strawberries don’t come too close to the edges. We have full control of how close or distant we want them to be, through this padding.

Note how we’re also using negative margins to compensate for the padding on our outer card wrapper, otherwise we’d get white space all around the image.

Use the object-fit property for inline images

As much as the previous demo works, we can still improve the approach. Up to now, we’ve assumed that the image was un-semantical content — but with this layout, it’s also likely that the image illustration could be more than decoration.

If that’s the case, we definitely don’t want the image to get cut off because that would essentially amount to data loss. It’s semantically better to put the image inline instead of a background to prevent that, and we can use the object-fit property to make it happen.

CodePen Embed Fallback

We’ve extracted the strawberries from the background and it’s now an inline <img> element, but we kept the background color in that same image div. 

Finally, combining the object-fit: contain with a 100% width makes it possible to resize the window and keep the aspect ratio of the strawberries. The caveat of this approach, however, is that we need to set a fixed height for the image on the desktop version — otherwise it’s going to follow the proportion of the set width (and reducing it will alter the layout). That might make things too constrained if we need to generate these cards with a variable amount of text that breaks into several lines.

Coming soon: aspect-ratio

The solution for the concern above might be just around the corner with the upcoming aspect-ratio property. This will enable setting a fixed ratio for an element, like this:

.el {
  aspect-ratio: 16 / 9;
}

This means we’ll be able to eliminate fixed height and replace it with our calculated aspect ratio. For example, the dimensions in the desktop breakpoint of our last example looked like this:

.image {
  /* ... */
  height: 184px;
  width: 318px;
}

With aspect-ratio, we could remove the height declaration and do the math to get the closest ratio that amounts to 184:

.image {
  /* ... */
  width: 318px; /*  Base width */
  height: unset; /* Resets the height that was set outside the media query */
  aspect-ratio: 159 / 92; /* Amounts close to a 184px height */
}

The upcoming property is better explored in this article, if you want to learn more about it.

In the end, there are multiple ways to achieve reliably responsive images in a variable proportion layout. However, the trick to make this job easier — and better — does not necessarily lie with CSS; it can be as simple as adapting your images, whether that’s by separating the foreground from background (like we did) or selecting specific images that will still work if a fair portion of the edges get cropped.

The post Fluid Images in a Variable Proportion Layout appeared first on CSS-Tricks.

Source: css tricks

Categories
Article jamstack learning

Settling down in a Jamstack world

One of the things I like about Jamstack is that it’s just a philosophy. It’s not particularly prescriptive about how you go about it. To me, the only real requirement is that it’s based on static (CDN-backed) hosting. You can use whatever tooling you like. Those tools, though, tend to be somewhat new, and new sometimes comes with issues. Some pragmatism from Sean C Davis here:

I have two problems with solving problems using the newest, best tool every time a problem arises.

1. It’s simply not productive. Introducing new processes and tools takes time. Mastery and efficiency are built over time. If we’re trying to run a profitable business, we shouldn’t start from scratch every time.

2. We can’t know everything, all the time. With the rapidity at which we’re seeing new tools, there’s simply no way of knowing the best tool for the job because there’s no way to know all the tools available.

The trick is to settle into some tools you’ve proved that work and then keep using them to increase that level of expertise.

The post Settling down in a Jamstack world appeared first on CSS-Tricks.

Source: css tricks

Categories
3D Printing Graphics

50 Sites to Download Free 3D Models – Best Of

3D printers have immensely revolutionized the art and manufacturing industry. With advancements in the 3D printer technology, it is now not very difficult to own one, even in your home or office….

Visit hongkiat.com for full content.
Source: hongkiat

Categories
Uncategorized

How To Test Your React Apps With The React Testing Library

How To Test Your React Apps With The React Testing Library

How To Test Your React Apps With The React Testing Library

Chidi Orji

2020-07-03T12:30:00+00:00
2020-07-05T00:11:03+00:00

Today, we’ll briefly discuss why it’s important to write automated tests for any software project, and shed light on some of the common types of automated testing. We’ll build a to-do list app by following the Test-Driven Development (TDD) approach. I’ll show you how to write both unit and functional tests, and in the process, explain what code mocks are by mocking a few libraries. I’ll be using a combination of RTL and Jest — both of which come pre-installed in any new project created with Create-React-App (CRA).

To follow along, you need to know how to set up and navigate a new React project and how to work with the yarn package manager (or npm). Familiarities with Axios and React-Router are also required.

Best Practices With React

React is a fantastic JavaScript library for building rich user interfaces. It provides a great component abstraction for organizing your interfaces into well-functioning code, and there’s just about anything you can use it for. Read more articles on React →

Why You Should Test Your Code

Before shipping your software to end-users, you first have to confirm that it is working as expected. In other words, the app should satisfy its project specifications.

Just as it is important to test our project as a whole before shipping it to end-users, it’s also essential to keep testing our code during the lifetime of a project. This is necessary for a number of reasons. We may make updates to our application or refactor some parts of our code. A third-party library may undergo a breaking change. Even the browser that is running our web application may undergo breaking changes. In some cases, something stops working for no apparent reason — things could go wrong unexpectedly. Thus, it is necessary to test our code regularly for the lifetime of a project.

Broadly speaking, there are manual and automated software tests. In a manual test, a real user performs some action on our application to verify that they work correctly. This kind of test is less reliable when repeated several times because it’s easy for the tester to miss some details between test runs.

In an automated test, however, a test script is executed by a machine. With a test script, we can be sure that whatever details we set in the script will remain unchanged on every test run.

This kind of test gives us the benefits of being predictable and fast, such that we can quickly find and fix bugs in our code.

Having seen the necessity of testing our code, the next logical question is, what sort of automated tests should we write for our code? Let’s quickly go over a few of them.

Types Of Automated Testing

There are many different types of automated software testing. Some of the most common ones are unit tests, integration tests, functional tests, end-to-end tests, acceptance tests, performance tests, and smoke tests.

  1. Unit test
    In this kind of test, the goal is to verify that each unit of our application, considered in isolation, is working correctly. An example would be testing that a particular function returns an expected value, give some known inputs. We’ll see several examples in this article.
  2. Smoke test
    This kind of test is done to check that the system is up and running. For example, in a React app, we could just render our main app component and call it a day. If it renders correctly we can be fairly certain that our app would render on the browser.
  3. Integration test
    This sort of test is carried out to verify that two or more modules can work well together. For example, you might run a test to verify that your server and database are actually communicating correctly.
  4. Functional test
    A functional test exists to verify that the system meets its functional specification. We’ll see an example later.
  5. End-to-end test
    This kind of test involves testing the application the same way it would be used in the real world. You can use a tool like cypress for E2E tests.
  6. Acceptance test
    This is usually done by the business owner to verify that the system meets specifications.
  7. Performance test
    This sort of testing is carried out to see how the system performs under significant load. In frontend development, this is usually about how fast the app loads on the browser.

There’s more here if you’re interested.

Why Use React Testing Library?

When it comes to testing React applications, there are a few testing options available, of which the most common ones I know of are Enzyme and React Testing Library (RTL).

RTL is a subset of the @testing-library family of packages. Its philosophy is very simple. Your users don’t care whether you use redux or context for state management. They care less about the simplicity of hooks nor the distinction between class and functional components. They just want your app to work in a certain way. It is, therefore, no surprise that the testing library’s primary guiding principle is

“The more your tests resemble the way your software is used, the more confidence they can give you.”

So, whatever you do, have the end-user in mind and test your app just as they would use it.

Choosing RTL gives you a number of advantages. First, it’s much easier to get started with it. Every new React project bootstrapped with CRA comes with RTL and Jest configured. The React docs also recommend it as the testing library of choice. Lastly, the guiding principle makes a lot of sense — functionality over implementation details.

With that out of the way, let’s get started with building a to-do list app, following the TDD approach.

Project Setup

Open a terminal and copy and run the below command.

# start new react project and start the server
npx create-react-app start-rtl && cd start-rtl && yarn start

This should create a new React project and start the server on http://localhost:3000. With the project running, open a separate terminal, run yarn test and then press a. This runs all tests in the project in watch mode. Running the test in watch mode means that the test will automatically re-run when it detects a change in either the test file or the file that is being tested. On the test terminal, you should see something like the picture below:

Initial test passing

Initial test passing. (Large preview)

You should see a lot of greens, which indicates that the test we’re running passed in flying colors.

As I mentioned earlier, CRA sets up RTL and Jest for every new React project. It also includes a sample test. This sample test is what we just executed.

When you run the yarn test command, react-scripts calls upon Jest to execute the test. Jest is a JavaScript testing framework that’s used in running tests. You won’t find it listed in package.json but you can do a search inside yarn.lock to find it. You can also see it in node_modules/.

Jest is incredible in the range of functionality that it provides. It provides tools for assertions, mocking, spying, etc. I strongly encourage you to take at least a quick tour of the documentation. There’s a lot to learn there that I cannot scratch in this short piece. We’ll be using Jest a lot in the coming sections.

Open package.json let’s see what we have there. The section of interest is dependencies.

  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    ...
  },

We have the following packages installed specifically for testing purpose:

  1. @testing-library/jest-dom: provides custom DOM element matchers for Jest.
  2. @testing-library/react: provides the APIs for testing React apps.
  3. @testing-library/user-event: provides advanced simulation of browser interactions.

Open up App.test.js let’s take a look at its content.

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  const { getByText } = render();
  const linkElement = getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

The render method of RTL renders the <App /> component and returns an object which is de-structured for the getByText query. This query finds elements in the DOM by their display text. Queries are the tools for finding elements in the DOM. The complete list of queries can be found here. All of the queries from the testing library are exported by RTL, in addition to the render, cleanup, and act methods. You can read more about these in the API section.

The text is matched with the regular expression /learn react/i. The i flag makes the regular expression case-insensitive. We expect to find the text Learn React in the document.

All of this mimics the behavior a user would experience in the browser when interacting with our app.

Let’s start making the changes required by our app. Open App.js and replace the content with the below code.

import React from "react";
import "./App.css";
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h2>Getting started with React testing library</h2>
      </header>
    </div>
  );
}
export default App;

If you still have the test running, you should see the test fail. Perhaps you can guess why that is the case, but we’ll return to it a bit later. Right now I want to refactor the test block.

Replace the test block in src/App.test.js with the code below:

# use describe, it pattern
describe("<App />", () => {
  it("Renders <App /> component correctly", () => {
    const { getByText } = render(<App />);
    expect(getByText(/Getting started with React testing library/i)).toBeInTheDocument();
  });
});

This refactor makes no material difference to how our test will run. I prefer the describe and it pattern as it allows me structure my test file into logical blocks of related tests. The test should re-run and this time it will pass. In case you haven’t guessed it, the fix for the failing test was to replace the learn react text with Getting started with React testing library.

In case you don’t have time to write your own styles you can just copy the one below into App.css.

.App {
  min-height: 100vh;
  text-align: center;
}
.App-header {
  height: 10vh;
  display: flex;
  background-color: #282c34;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}
.App-body {
  width: 60%;
  margin: 20px auto;
}
ul {
  padding: 0;
  display: flex;
  list-style-type: decimal;
  flex-direction: column;
}
li {
  font-size: large;
  text-align: left;
  padding: 0.5rem 0;
}
li a {
  text-transform: capitalize;
  text-decoration: none;
}
.todo-title {
  text-transform: capitalize;
}
.completed {
  color: green;
}
.not-completed {
  color: red;
}

You should already see the page title move up after adding this CSS.

I consider this a good point for me to commit my changes and push to Github. The corresponding branch is 01-setup.

Let’s continue with our project setup. We know we’re going to need some navigation in our app so we need React-Router. We’ll also be making API calls with Axios. Let’s install both.

# install react-router-dom and axios
yarn add react-router-dom axios

Most React apps you’ll build will have to maintain state. There’s a lot of libraries available for managing state. But for this tutorial, I’ll be using React’s context API and the useContext hook. So let’s set up our app’s context.

Create a new file src/AppContext.js and enter the below content.

import React from "react";
export const AppContext = React.createContext({});

export const AppProvider = ({ children }) => {
  const reducer = (state, action) => {
    switch (action.type) {
      case "LOAD_TODOLIST":
        return { ...state, todoList: action.todoList };
      case "LOAD_SINGLE_TODO":
        return { ...state, activeToDoItem: action.todo };
      default:
        return state;
    }
  };
  const [appData, appDispatch] = React.useReducer(reducer, {
    todoList: [],
    activeToDoItem: { id: 0 },
  });
  return (
    <AppContext.Provider value={{ appData, appDispatch }}>
      {children}
    </AppContext.Provider>
  );
};

Here we create a new context with React.createContext({}), for which the initial value is an empty object. We then define an AppProvider component that accepts children component. It then wraps those children in AppContext.Provider, thus making the { appData, appDispatch } object available to all children anywhere in the render tree.

Our reducer function defines two action types.

  1. LOAD_TODOLIST which is used to update the todoList array.
  2. LOAD_SINGLE_TODO which is used to update activeToDoItem.

appData and appDispatch are both returned from the useReducer hook. appData gives us access to the values in the state while appDispatch gives us a function which we can use to update the app’s state.

Now open index.js, import the AppProvider component and wrap the <App /> component with <AppProvider />. Your final code should look like what I have below.

import { AppProvider } from "./AppContext";

ReactDOM.render(
  <React.StrictMode>
    <AppProvider>
      <App />
    </AppProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

Wrapping <App /> inside <AppProvider /> makes AppContext available to every child component in our app.

Remember that with RTL, the aim is to test our app the same way a real user would interact with it. This implies that we also want our tests to interact with our app state. For that reason, we also need to make our <AppProvider /> available to our components during tests. Let’s see how to make that happen.

The render method provided by RTL is sufficient for simple components that don’t need to maintain state or use navigation. But most apps require at least one of both. For this reason, it provides a wrapper option. With this wrapper, we can wrap the UI rendered by the test renderer with any component we like, thus creating a custom render. Let’s create one for our tests.

Create a new file src/custom-render.js and paste the following code.

import React from "react";
import { render } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";

import { AppProvider } from "./AppContext";

const Wrapper = ({ children }) => {
  return (
    <AppProvider>
      <MemoryRouter>{children}</MemoryRouter>
    </AppProvider>
  );
};

const customRender = (ui, options) =>
  render(ui, { wrapper: Wrapper, ...options });

// re-export everything
export * from "@testing-library/react";

// override render method
export { customRender as render };

Here we define a <Wrapper /> component that accepts some children component. It then wraps those children inside <AppProvider /> and <MemoryRouter />. MemoryRouter is

A <Router> that keeps the history of your “URL” in memory (does not read or write to the address bar). Useful in tests and non-browser environments like React Native.

We then create our render function, providing it the Wrapper we just defined through its wrapper option. The effect of this is that any component we pass to the render function is rendered inside <Wrapper />, thus having access to navigation and our app’s state.

The next step is to export everything from @testing-library/react. Lastly, we export our custom render function as render, thus overriding the default render.

Note that even if you were using Redux for state management the same pattern still applies.

Let’s now make sure our new render function works. Import it into src/App.test.js and use it to render the <App /> component.

Open App.test.js and replace the import line. This

import { render } from '@testing-library/react';

should become

import { render } from './custom-render';

Does the test still pass? Good job.

There’s one small change I want to make before wrapping up this section. It gets tiring very quickly to have to write const { getByText } and other queries every time. So, I’m going to be using the screen object from the DOM testing library henceforth.

Import the screen object from our custom render file and replace the describe block with the code below.

import { render, screen } from "./custom-render";

describe("<App />", () => {
  it("Renders <App /> component correctly", () => {
    render(<App />);
    expect(
      screen.getByText(/Getting started with React testing library/i)
    ).toBeInTheDocument();
  });
});

We’re now accessing the getByText query from the screen object. Does your test still pass? I’m sure it does. Let’s continue.

If your tests don’t pass you may want to compare your code with mine. The corresponding branch at this point is 02-setup-store-and-render.

Testing And Building The To-Do List Index Page

In this section, we’ll pull to-do items from http://jsonplaceholder.typicode.com/. Our component specification is very simple. When a user visits our app homepage,

  1. show a loading indicator that says Fetching todos while waiting for the response from the API;
  2. display the title of 15 to-do items on the screen once the API call returns (the API call returns 200). Also, each item title should be a link that will lead to the to-do details page.

Following a test-driven approach, we’ll write our test before implementing the component logic. Before doing that we’ll need to have the component in question. So go ahead and create a file src/TodoList.js and enter the following content:

import React from "react";
import "./App.css";
export const TodoList = () => {
  return (
    <div>
    </div>
  );
};

Since we know the component specification we can test it in isolation before incorporating it into our main app. I believe it’s up to the developer at this point to decide how they want to handle this. One reason you might want to test a component in isolation is so that you don’t accidentally break any existing test and then having to fight fires in two locations. With that out of the way let’s now write the test.

Create a new file src/TodoList.test.js and enter the below code:

import React from "react";
import axios from "axios";
import { render, screen, waitForElementToBeRemoved } from "./custom-render";
import { TodoList } from "./TodoList";
import { todos } from "./makeTodos";

describe("<App />", () => {
  it("Renders <TodoList /> component", async () => {
    render(<TodoList />);
    await waitForElementToBeRemoved(() => screen.getByText(/Fetching todos/i));

    expect(axios.get).toHaveBeenCalledTimes(1);
    todos.slice(0, 15).forEach((td) => {
      expect(screen.getByText(td.title)).toBeInTheDocument();
    });
  });
});

Inside our test block, we render the <TodoList /> component and use the waitForElementToBeRemoved function to wait for the Fetching todos text to disappear from the screen. Once this happens we know that our API call has returned. We also check that an Axios get call was fired once. Finally, we check that each to-do title is displayed on the screen. Note that the it block receives an async function. This is necessary for us to be able to use await inside the function.

Each to-do item returned by the API has the following structure.

{
  id: 0,
  userId: 0,
  title: 'Some title',
  completed: true,
}

We want to return an array of these when we

import { todos } from "./makeTodos"

The only condition is that each id should be unique.

Create a new file src/makeTodos.js and enter the below content. This is the source of todos we’ll use in our tests.

const makeTodos = (n) => {
  // returns n number of todo items
  // default is 15
  const num = n || 15;
  const todos = [];
  for (let i = 0; i < num; i++) {
    todos.push({
      id: i,
      userId: i,
      title: `Todo item ${i}`,
      completed: [true, false][Math.floor(Math.random() * 2)],
    });
  }
  return todos;
};

export const todos = makeTodos(200);

This function simply generates a list of n to-do items. The completed line is set by randomly choosing between true and false.

Unit tests are supposed to be fast. They should run within a few seconds. Fail fast! This is one of the reasons why letting our tests make actual API calls is impractical. To avoid this we mock such unpredictable API calls. Mocking simply means replacing a function with a fake version, thus allowing us to customize the behavior. In our case, we want to mock the get method of Axios to return whatever we want it to. Jest already provides mocking functionality out of the box.

Let’s now mock Axios so it returns this list of to-dos when we make the API call in our test. Create a file src/__mocks__/axios.js and enter the below content:

import { todos } from "../makeTodos";

export default {
  get: jest.fn().mockImplementation((url) => {
    switch (url) {
      case "https://jsonplaceholder.typicode.com/todos":
        return Promise.resolve({ data: todos });
      default:
        throw new Error(`UNMATCHED URL: ${url}`);
    }
  }),
};

When the test starts, Jest automatically finds this mocks folder and instead of using the actual Axios from node_modules/ in our tests, it uses this one. At this point, we’re only mocking the get method using Jest’s mockImplementation method. Similarly, we can mock other Axios methods like post, patch, interceptors, defaults etc. Right now they’re all undefined and any attempt to access, axios.post for example, would result in an error.

Note that we can customize what to return based on the URL the Axios call receives. Also, Axios calls return a promise which resolves to the actual data we want, so we return a promise with the data we want.

At this point, we have one passing test and one failing test. Let’s implement the component logic.

Open src/TodoList.js let’s build out the implementation piece by piece. Start by replacing the code inside with this one below.

import React from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import "./App.css";
import { AppContext } from "./AppContext";

export const TodoList = () => {
  const [loading, setLoading] = React.useState(true);
  const { appData, appDispatch } = React.useContext(AppContext);

  React.useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/todos").then((resp) => {
      const { data } = resp;
      appDispatch({ type: "LOAD_TODOLIST", todoList: data });
      setLoading(false);
    });
  }, [appDispatch, setLoading]);

  return (
    <div>
      // next code block goes here
    </div>
  );
};

We import AppContext and de-structure appData and appDispatch from the return value of React.useContext. We then make the API call inside a useEffect block. Once the API call returns, we set the to-do list in state by firing the LOAD_TODOLIST action. Finally, we set the loading state to false to reveal our to-dos.

Now enter the final piece of code.

{loading ? (
  <p>Fetching todos</p>
) : (
  <ul>
    {appData.todoList.slice(0, 15).map((item) => {
      const { id, title } = item;
      return (
        <li key={id}>
          <Link to={`/item/${id}`} data-testid={id}>
            {title}
          </Link>
        </li>
      );
    })}
  </ul>
)}

We slice appData.todoList to get the first 15 items. We then map over those and render each one in a <Link /> tag so we can click on it and see the details. Note the data-testid attribute on each Link. This should be a unique ID that will aid us in finding individual DOM elements. In a case where we have similar text on the screen, we should never have the same ID for any two elements. We’ll see how to use this a bit later.

My tests now pass. Does yours pass? Great.

Let’s now incorporate this component into our render tree. Open up App.js let’s do that.

First things. Add some imports.

import { BrowserRouter, Route } from "react-router-dom";
import { TodoList } from "./TodoList";

We need BrowserRouter for navigation and Route for rendering each component in each navigation location.

Now add the below code after the <header /> element.

<div className="App-body">
  <BrowserRouter>
    <Route exact path="/" component={TodoList} />
  </BrowserRouter>
</div>

This is simply telling the browser to render the <TodoList /> component when we’re on the root location, /. Once this is done, our tests still pass but you should see some error messages on your console telling you about some act something. You should also see that the <TodoList /> component seems to be the culprit here.

Terminal showing act warnings

Terminal showing act warnings. (Large preview)

Since we’re sure that our TodoList component by itself is okay, we have to look at the App component, inside of which is rendered the <TodoList /> component.

This warning may seem complex at first but it is telling us that something is happening in our component that we’re not accounting for in our test. The fix is to wait for the loading indicator to be removed from the screen before we proceed.

Open up App.test.js and update the code to look like so:

import React from "react";
import { render, screen, waitForElementToBeRemoved } from "./custom-render";
import App from "./App";
describe("<App />", () => {
  it("Renders <App /> component correctly", async () => {
    render(<App />);
    expect(
      screen.getByText(/Getting started with React testing library/i)
    ).toBeInTheDocument();
    await waitForElementToBeRemoved(() => screen.getByText(/Fetching todos/i));
  });
});

We’ve made two changes. First, we changed the function in the it block to an async function. This is a necessary step to allow us to use await in the function body. Secondly, we wait for the Fetching todos text to be removed from the screen. And voila!. The warning is gone. Phew! I strongly advise that you bookmark this post by Kent Dodds for more on this act warning. You’re gonna need it.

Now open the page in your browser and you should see the list of to-dos. You can click on an item if you like, but it won’t show you anything because our router doesn’t yet recognize that URL.

For comparison, the branch of my repo at this point is 03-todolist.

Let’s now add the to-do details page.

Testing And Building The Single To-Do Page

To display a single to-do item we’ll follow a similar approach. The component specification is simple. When a user navigates to a to-do page:

  1. display a loading indicator that says Fetching todo item id where id represents the to-do’s id, while the API call to https://jsonplaceholder.typicode.com/todos/item_id runs.
  2. When the API call returns, show the following information:
    • Todo item title
    • Added by: userId
    • This item has been completed if the to-do has been completed or
    • This item is yet to be completed if the to-do has not been completed.

Let’s start with the component. Create a file src/TodoItem.js and add the following content.

import React from "react";
import { useParams } from "react-router-dom";

import "./App.css";

export const TodoItem = () => {
  const { id } = useParams()
  return (
    <div className="single-todo-item">
    </div>
  );
};

The only thing new to us in this file is the const { id } = useParams() line. This is a hook from react-router-dom that lets us read URL parameters. This id is going to be used in fetching a to-do item from the API.

This situation is a bit different because we’re going to be reading the id from the location URL. We know that when a user clicks a to-do link, the id will show up in the URL which we can then grab using the useParams() hook. But here we’re testing the component in isolation which means that there’s nothing to click, even if we wanted to. To get around this we’ll have to mock react-router-dom, but only some parts of it. Yes. It’s possible to mock only what we need to. Let’s see how it’s done.

Create a new mock file src/__mocks__ /react-router-dom.js. Now paste in the following code:

module.exports = {
  ...jest.requireActual("react-router-dom"),
  useParams: jest.fn(),
};

By now you should have noticed that when mocking a module we have to use the exact module name as the mock file name.

Here, we use the module.exports syntax because react-router-dom has mostly named exports. (I haven’t come across any default export since I’ve been working with it. If there are any, kindly share with me in the comments). This is unlike Axios where everything is bundled as methods in one default export.

We first spread the actual react-router-dom, then replace the useParams hook with a Jest function. Since this function is a Jest function, we can modify it anytime we want. Keep in mind that we’re only mocking the part we need to because if we mock everything, we’ll lose the implementation of MemoryHistory which is used in our render function.

Let’s start testing!

Now create src/TodoItem.test.js and enter the below content:

import React from "react";
import axios from "axios";
import { render, screen, waitForElementToBeRemoved } from "./custom-render";
import { useParams, MemoryRouter } from "react-router-dom";
import { TodoItem } from "./TodoItem";

describe("<TodoItem />", () => {
  it("can tell mocked from unmocked functions", () => {
    expect(jest.isMockFunction(useParams)).toBe(true);
    expect(jest.isMockFunction(MemoryRouter)).toBe(false);
  });
});

Just like before, we have all our imports. The describe block then follows. Our first case is only there as a demonstration that we’re only mocking what we need to. Jest’s isMockFunction can tell whether a function is mocked or not. Both expectations pass, confirming the fact that we have a mock where we want it.

Add the below test case for when a to-do item has been completed.

  it("Renders <TodoItem /> correctly for a completed item", async () => {
    useParams.mockReturnValue({ id: 1 });
    render(<TodoItem />);

    await waitForElementToBeRemoved(() =>
      screen.getByText(/Fetching todo item 1/i)
    );

    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(screen.getByText(/todo item 1/)).toBeInTheDocument();
    expect(screen.getByText(/Added by: 1/)).toBeInTheDocument();
    expect(
      screen.getByText(/This item has been completed/)
    ).toBeInTheDocument();
  });

The very first thing we do is to mock the return value of useParams. We want it to return an object with an id property, having a value of 1. When this is parsed in the component, we end up with the following URL https://jsonplaceholder.typicode.com/todos/1. Keep in mind that we have to add a case for this URL in our Axios mock or it will throw an error. We will do that in just a moment.

We now know for sure that calling useParams() will return the object { id: 1 } which makes this test case predictable.

As with previous tests, we wait for the loading indicator, Fetching todo item 1 to be removed from the screen before making our expectations. We expect to see the to-do title, the id of the user who added it, and a message indicating the status.

Open src/__mocks__/axios.js and add the following case to the switch block.

      case "https://jsonplaceholder.typicode.com/todos/1":
        return Promise.resolve({
          data: { id: 1, title: "todo item 1", userId: 1, completed: true },
        });

When this URL is matched, a promise with a completed to-do is returned. Of course, this test case fails since we’re yet to implement the component logic. Go ahead and add a test case for when the to-do item has not been completed.

  it("Renders <TodoItem /> correctly for an uncompleted item", async () => {
    useParams.mockReturnValue({ id: 2 });
    render(<TodoItem />);
    await waitForElementToBeRemoved(() =>
      screen.getByText(/Fetching todo item 2/i)
    );
    expect(axios.get).toHaveBeenCalledTimes(2);
    expect(screen.getByText(/todo item 2/)).toBeInTheDocument();
    expect(screen.getByText(/Added by: 2/)).toBeInTheDocument();
    expect(
      screen.getByText(/This item is yet to be completed/)
    ).toBeInTheDocument();
  });

This is the same as the previous case. The only difference is the ID of the to-do, the userId, and the completion status. When we enter the component, we’ll need to make an API call to the URL https://jsonplaceholder.typicode.com/todos/2. Go ahead and add a matching case statement to the switch block of our Axios mock.

case "https://jsonplaceholder.typicode.com/todos/2":
  return Promise.resolve({
    data: { id: 2, title: "todo item 2", userId: 2, completed: false },
  });

When the URL is matched, a promise with an uncompleted to-do is returned.

Both test cases are failing. Now let’s add the component implementation to make them pass.

Open src/TodoItem.js and update the code to the following:

import React from "react";
import axios from "axios";
import { useParams } from "react-router-dom";
import "./App.css";
import { AppContext } from "./AppContext";

export const TodoItem = () => {
  const { id } = useParams();
  const [loading, setLoading] = React.useState(true);
  const {
    appData: { activeToDoItem },
    appDispatch,
  } = React.useContext(AppContext);

  const { title, completed, userId } = activeToDoItem;
  React.useEffect(() => {
    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${id}`)
      .then((resp) => {
        const { data } = resp;
        appDispatch({ type: "LOAD_SINGLE_TODO", todo: data });
        setLoading(false);
      });
  }, [id, appDispatch]);
  return (
    <div className="single-todo-item">
      // next code block goes here.
    </div>
  );
};

As with the <TodoList /> component, we import AppContext. We read activeTodoItem from it, then we read the to-do title, userId, and completion status. After that we make the API call inside a useEffect block. When the API call returns we set the to-do in state by firing the LOAD_SINGLE_TODO action. Finally, we set our loading state to false to reveal the to-do details.

Let’s add the final piece of code inside the return div:

{loading ? (
  <p>Fetching todo item {id}</p>
) : (
  <div>
    <h2 className="todo-title">{title}</h2>
    <h4>Added by: {userId}</h4>
    {completed ? (
      <p className="completed">This item has been completed</p>
    ) : (
      <p className="not-completed">This item is yet to be completed</p>
    )}
  </div>
)}

Once this is done all tests should now pass. Yay! We have another winner.

Our component tests now pass. But we still haven’t added it to our main app. Let’s do that.

Open src/App.js and add the import line:

import { TodoItem } from './TodoItem'

Add the TodoItem route above the TodoList route. Be sure to preserve the order shown below.

# preserve this order
<Route path="/item/:id" component={TodoItem} />
<Route exact path="/" component={TodoList} />

Open your project in your browser and click on a to-do. Does it take you to the to-do page? Of course, it does. Good job.

In case you’re having any problem, you can check out my code at this point from the 04-test-todo branch.

Phew! This has been a marathon. But bear with me. There’s one last point I’d like us to touch. Let’s quickly have a test case for when a user visits our app, and then proceed to click on a to-do link. This is a functional test to mimic how our app should work. In practice, this is all the testing we need to be done for this app. It ticks every box in our app specification.

Open App.test.js and add a new test case. The code is a bit long so we’ll add it in two steps.

import userEvent from "@testing-library/user-event";
import { todos } from "./makeTodos";

jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"),
}));

describe("<App />"
  ...
  // previous test case
  ...

  it("Renders todos, and I can click to view a todo item", async () => {
    render(<App />);
    await waitForElementToBeRemoved(() => screen.getByText(/Fetching todos/i));
    todos.slice(0, 15).forEach((td) => {
      expect(screen.getByText(td.title)).toBeInTheDocument();
    });
    // click on a todo item and test the result
    const { id, title, completed, userId } = todos[0];
    axios.get.mockImplementationOnce(() =>
      Promise.resolve({
        data: { id, title, userId, completed },
      })
    );
    userEvent.click(screen.getByTestId(String(id)));
    await waitForElementToBeRemoved(() =>
      screen.getByText(`Fetching todo item ${String(id)}`)
    );

    // next code block goes here
  });
});

We have two imports of which userEvent is new. According to the docs,

user-event is a companion library for the React Testing Library that provides a more advanced simulation of browser interactions than the built-in fireEvent method.”

Yes. There is a fireEvent method for simulating user events. But userEvent is what you want to be using henceforth.

Before we start the testing process, we need to restore the original useParams hooks. This is necessary since we want to test actual behavior, so we should mock as little as possible. Jest provides us with requireActual method which returns the original react-router-dom module.

Note that we must do this before we enter the describe block, otherwise, Jest would ignore it. It states in the documentation that requireActual:

“…returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.”

Once this is done, Jest bypasses every other check and ignores the mocked version of the react-router-dom.

As usual, we render the <App /> component and wait for the Fetching todos loading indicator to disappear from the screen. We then check for the presence of the first 15 to-do items on the page.

Once we’re satisfied with that, we grab the first item in our to-do list. To prevent any chance of a URL collision with our global Axios mock, we override the global mock with Jest’s mockImplementationOnce. This mocked value is valid for one call to the Axios get method. We then grab a link by its data-testid attribute and fire a user click event on that link. Then we wait for the loading indicator for the single to-do page to disappear from the screen.

Now finish the test by adding the below expectations in the position indicated.

expect(screen.getByText(title)).toBeInTheDocument();
expect(screen.getByText(`Added by: ${userId}`)).toBeInTheDocument();
switch (completed) {
  case true:
    expect(
      screen.getByText(/This item has been completed/)
    ).toBeInTheDocument();
    break;
  case false:
    expect(
      screen.getByText(/This item is yet to be completed/)
    ).toBeInTheDocument();
    break;
  default:
    throw new Error("No match");
    }
  

We expect to see the to-do title and the user who added it. Finally, since we can’t be sure about the to-do status, we create a switch block to handle both cases. If a match is not found we throw an error.

You should have 6 passing tests and a functional app at this point. In case you’re having trouble, the corresponding branch in my repo is 05-test-user-action.

Conclusion

Phew! That was some marathon. If you made it to this point, congratulations. You now have almost all you need to write tests for your React apps. I strongly advise that you read CRA’s testing docs and RTL’s documentation. Overall both are relatively short and direct.

I strongly encourage you to start writing tests for your React apps, no matter how small. Even if it’s just smoke tests to make sure your components render. You can incrementally add more test cases over time.

Smashing Editorial
(ks, ra, yk, il)

Source: smash mag

Categories
Community & Inspiration diversity in tech diversity in web design ethnic minorities who code girls who code women who code

Diversity Initiatives in Web Design

Web developers have been the bedrock of any company’s business strategy for some time, and the industry is continuing to thrive and grow at a rapid pace. This is why it’s surprising that it is so lacklustre when it comes to diversity.

A recent study revealed 80% of those in the design industry are male, and more specifically 79% within the field of web design. According to WISE, just 23% of the people working in STEM roles (Science, Technology, Engineering and Maths) are female and women currently account for just 15.8% of the UK’s current generation of engineering and technology graduates.

Why the Lack of Diversity in Web Design?

The main reason for this, as cited by the Organisation for Economic Co-operation and Development (OECD) found that women still lack the confidence to pursue these careers, despite their school results being as good as (or better) than their male counterparts. Research has found that the professional and technical services sector has the fourth-highest gender pay gap of all UK industries. If more women were to join these higher-paid sectors it could help reduce the gender pay gap as a whole, as well as help female economic empowerment.

This division is seen in ethnic minority groups too. The numbers for BAME (Black, Asian, Minority Ethnic) employees in the British tech industry are unknown but is estimated by the British Computer Society to be at 1-2%, a ridiculously low number in this day and age. This is why groups and organisations are cropping up designed to promote an industry that reflects all of society rather than one part of it. Here are some of the organisations to pay attention to who are bridging the diversity gaps in web design.

Girls Who Code

Girls Who Code are working to create opportunities for women within tech, aiming to deepen their computer science skills and confidence. They run a range of programs designed to equip women with the necessary computing skills to pursue opportunities in the field and to give chances that are often shunned due to society. Founder Saujani states that women are socialized to seek perfection, and this is something that needs to be overcome. One way to break that mentality at an early age, she says, is coding:

[Girls] walk into these classrooms and they feel like they will never be good at it, and when they learn how to create something, whether it’s a website or app, it changes their mindset and they stop giving up

Adobe Design Circle

Adobe Design Circle is another initiative aiming to introduce all members of society to design. They want to create more visibility for design as a viable career path for anyone that might be considering it, and to help with youth entering the field. This is opening the opportunities of working in tech and web to aspiring designers at a young age who aren’t necessarily yet conditioned by the pressures of society and showing them it can be a realistic career path.

They have their own scholarships and mentoring initiative to support these goals too. The faces behind the team of Adobe Design Circle range through multiple ethnicities and have a fairly even male-female divide. This equal representation alone is inspiring. One of Adobe’s core missions is to offer youth the opportunity to learn and express themselves through creativity and technology, regardless of their economic or cultural backgrounds. With this they specifically encourage applicants of all backgrounds to apply and offer many other opportunities from mentoring to internships.

Ladies that UX

Ladies that UX are a collaborative community of women in UX aiming to “support each other, push the UX boundaries and promote female skill and talent.” It is a European-based initiative where each city involved runs slightly different events and groups decide together what they would like to get from their meetups. They assist each other with UX challenges, discuss topics, and brainstorm ideas. Ladies that UX was created in 2013 by Georgie Bottomley and Lizzie Dyson with the aim of bringing together women in the industry, offering support and creating connections around the world.

Xuntos

Xuntos is aiming to create the largest community of ambitious and talented individuals from under-represented groups in the technology industry. It works to nurture university students and recent graduates that are often overlooked in the tech industry by the means of educational workshops, university hubs, events and an active community. The very name “Xuntos” is a Galician word which means “together” and this is their most important factor. They want people to realise they are not alone and just because the representation isn’t there, doesn’t mean their capabilities aren’t.

Colorintech

Colorintech is a non-profit organisation that was founded in 2016. It aims to close the gap and shorten the learning curve, with a strong community designed to help each other. The company was founded by Silicon Valley tech executive Dion McKenzie and ex-Googler Ashleigh Ainsley after they became frustrated at the few black individuals in the field. Since its inception 30,000 students, professionals, volunteers and tech companies have been impacted by their work, and over 450 minorities graduated from their programs in 2019 alone.

UKBlackTech

UKBlackTech are on a mission to create the most diverse tech sector in the world. Their aim is to encourage more ethnic minorities to enter the UK’s technology workforce and make an impact. To help with this, they design and implement different initiatives to help them get employed and retain employment, put on bespoke events that target aspects such as specific job roles or tech topics and promote different opportunities for members to apply to.

Witty Careers

Witty Careers was created with the aim to support women from black and ethnic minority backgrounds in the UK and equip them with the skills to build a career in the tech industry. They run different practical skills workshops and events which in the past have included visits to a Microsoft store, Uber, and Pivotal. They open doors for communications, networking and future career prospects for those in the minority. They also have a handy range of resources designed to help you get into the career you want. From CV writing advice to industry insights, they are all free of charge.

 

Featured image via Unsplash.

Source

p img {display:inline-block; margin-right:10px;}
.alignleft {float:left;}
p.showcase {clear:both;}
body#browserfriendly p, body#podcast p, div#emailbody p{margin:0;}

Source: Web Designer Depot

Categories
Article performance

Some Performance Links

Just had a couple of good performance links burning a hole in my pocket, so blogging them like a good little blogger.

Web Performance Recipes With Puppeteer

Puppeteer is an Node library for spinning up a copy of Chrome “headlessly” (i.e. no UI) and controlling it. People use it for stuff like taking a screenshot of a website or running integration tests. You can even run it in a Lambda.

Another use case is running synthetic (i.e. not based on real-users) performance tests, like some of these new Web Core Vitals

Addy Osmani lists out a bunch of these “recipes” for measuring certain performance things in Puppeteer. These would be super useful as part of a build process alongside other tests. Did the unit tests pass? Did the integration tests pass? Did the accessibility tests pass? Did the performance metrics tests pass?


BrowserStack SpeedLab

BrowserStack released a thing to measure your site and give you a performance score.

You get the tests back super quick which is cool. I can see how tools like this are good for starting conversations with teams about improving performance.

But… that number seems a little weird. They don’t exactly document how it’s calculated, but it seems to be based on stuff like Time to First Byte (TTFB) and the page load event, which aren’t particularly useful performance metrics.

It’s not bad that this tool exists or anything, but I don’t think it’s for practitioners doing performance work.


5 Common Mistakes Teams Make When Tracking Performance

Karolina Szczur from Calibre documents some common team struggles like, for example, having a team be able to identify real issues from variability noise.

Many people from different backgrounds can view performance dashboards. Not knowing what constitutes a meaningful change that needs investigation can result in false positives, lack of trust in monitoring and cycles spent looking for reasons for performance regressions or upgrades that aren’t there.


Are your JavaScript long tasks frustrating users?

50ms. That’s how long until any particular JavaScript task starts affecting user experience. Might as well track and (ideally) fix them.

When the browser’s main thread hits max CPU for more than 50ms, a user starts to notice that their clicks are delayed and that scrolling the page has become janky and unresponsive. Batteries drain faster. People rage click or go elsewhere.

The post Some Performance Links appeared first on CSS-Tricks.

Source: css tricks

Categories
Link

Refreshing Sidebar for 2020

The new design for Sidebar is lovely. I like how it goes even deeper with the sticky elements than the last design.

But even more notably, Sacha Greif has been posting five links per day to Sidebar since 2012. That’s a remarkable achievement.

Direct Link to ArticlePermalink

The post Refreshing Sidebar for 2020 appeared first on CSS-Tricks.

Source: css tricks

Categories
Uncategorized

Collective #612



60 Days of Animation

The Undead Institute offers books on HTML, CSS, Responsive Design and more that marry humor, excellent teaching, and brain-lodging practice for an experience that’ll outlive the apocalypse.

Check it out




Stryve

A new community for tech enthusiasts to share, learn, and build their careers.

Check it out


The design systems between us

Ethan Marcotte shares his thoughts on why he believes that design systems haven’t brought rich, cross-functional collaboration to most organizations.

Read it









Profiled

With Profiled you can create a developer portfolio from your GitHub account.

Check it out


Is WebP really better than JPEG?

According to Google, WebP is 25 – 34% smaller than JPEG at equivalent quality. But how much of it is really true? Find out in this article by Johannes Siipola.

Read it









The post Collective #612 appeared first on Codrops.


Source: codrops

Categories
Article

When a Line Doesn’t Break

We expect a line to break when the text on that line reaches the parent box boundaries. We see this every time we create a paragraph, just like this one. When the parent box doesn’t have enough room for the next word in a line, it breaks it and moves down to the next line and repeats that process.

Well, that’s how it works when words are separated by spaces or other whitespace. As far as CSS goes, there are five (!) properties that can possibly affect how and when a line breaks. Let’s not get into all that again though. Let’s instead look at a situation where it seems like a line is going to break but it doesn’t as an excuse to learn a little something about line breaking.

What happens in a situation where there is no way for the browser to know when it’s OK to make a break?

Let’s get ourselves into a bad situation with a “tag list” and then get ourselves out of it. Here’s our markup:

<ul>
  <li>PHP</li>
  <li>JavaScript</li>
  <li>Rust</li>
  <!-- etc. -->
</ul>

Next, we’ll apply CSS that overwrites the default list style from its default vertical orientation to horizontal by making the list items display inline.

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}


li {
  display: inline;
  padding-right: 5px;
}
CodePen Embed Fallback

The list looks just like we want it. I added a little bit of space between one list item and another, so it doesn’t look too crowded.

Now let’s introduce a wrapper element to the mix. That’s essentially a div around the unordered list. We can give it a class, say, .tags.

<div class="tags">
  <ul>
    <li>PHP</li>
    <li>JavaScript</li>
    <li>Rust</li>
  </ul>
</div>

Let’s say we want to give the wrapper a fixed width of 200px. That’s where we should expect to see line breaks happen as the unordered list bumps into wrapper’s boundaries.

.tags {
  width: 200px;
}
CodePen Embed Fallback

Here comes the interesting part. Many people use minifiers in their build process to reduce file sizes by getting rid of unnecessary values. Some of these values are whitespaces, which includes spaces, tabs, and line breaks (such as carriage return and line feed) characters that are use for formatting purposes but considered by minifies to be irrelevant to the final result.

If we “minify” our HTML by removing new lines, then this is what we get:

<div class="tags"><ul><li>PHP</li><li>JavaScript</li><li>Rust</li></ul></div>
CodePen Embed Fallback

UH OH. As you can see, the list is not breaking at the 200px boundary anymore. Why? What is different now? Personally, I thought HTML didn’t care about whitespaces. What is so different about the minified version from the original markup?

The browser does actually care about whitespaces… but only sometimes. And this just so happens to be one of those instances. When the page is being parsed, the parser sees this list as one long word because, from its perspective, there are no characters that differentiate one from the other.

One might think having the padding is affecting things. But if we remove the padding from our list items we still get the same result… only with no spacing between items.

CodePen Embed Fallback

The browser sees the entire list as a single word.

We can get natural line breaks from special characters

Besides spaces, excluding non-breaking spaces (&nbsp;), there are some other characters that will force a line break, including:

  • After hyphen (-)
  • After en dash ()
  • Before and after em dash ()
  • After question mark (?)
  • Zero-width white space (U+200B or )

These line breaks happen at rendering time which means the browser still sees this as one long word. Adding a new list item to the tag list with any of these characters will force a line break. Let’s add “Objective-C” to the list. Its name contains a hyphen, which we can use to see how it affects things.

For better readability purpose the code code will have indentation and new line.

<div class="tags">
  <ul>
    <li>PHP</li>
    <li>JavaScript</li>
    <li>Rust</li>
    <li>Objective-C</li>
  </ul>
</div>
CodePen Embed Fallback

That’s good. Let’s look at three solutions to our non-line-breaking list along these lines.

Solution 1: Add one of the breaking characters

We can keep forcing line breaks with those breaking characters like we just did. But remember, if you are using a minifier, adding the spaces in or after the closing tag won’t guaranteed it won’t be removed, as not all minifiers work the same way.

<div class="tags">
  <ul>
    <li>PHP </li>
    <li>JavaScript </li>
    <li>Rust </li>
    <li>Objective-C </li>
  </ul>
</div>
CodePen Embed Fallback

Solution 2: Use pseudo-elements

The breaking character can also be added using the ::before and ::after pseudo-elements in CSS. What makes this solution effective is that it’s not affected by an HTML minifier because the whitespace is added when the CSS is applied.

But, before we move on, let’s talk a moment about collapsing whitespaces.

The browser collapses whitespace before and after a character that forces a line break inside inline elements. With this in mind, there’s a little trick to using ::after and the content property with whitespacing and display: inline-block. The inline-block element adds a breaking character at the end of the text. Then the content property space comes after the breaking character created by the inline-block element, which results in the space being removed at rendering time. That is, unless the white-space property is set to pre.

CodePen Embed Fallback

Solution 3: Use inline-block instead

Perhaps you have bumped into a fight with space between inline-block elements in CSS before. We can use the inline-block value on the display  property to force a line break because the inline-block element already has the extra whitespace we need. This works similar to adding a zero-width space character, but the list items will have no visual separation.

CodePen Embed Fallback

Solution 4: Use flex or inline-flex

Another solution is to define the unordered list as a flex container, which allows us to use flex-flow to set the direction of the list and to make sure it to multiple lines when needed.

We can also turn to the display: inline-flex instead of inline-block solution. The idea here is that the entire flexible container display inline.


So, we started this post with a situation that might come up when using a minifier. That said, minifiers — and many libraries for that matter — are smart and will try to prevent this line-breaking issue from happening.

Sure, it’s not an extremely common situation to bump into. It’s really one of those things that can fly under the radar if we’re not paying attention but, if it does happen, at least we know there are ways to work around it.

The post When a Line Doesn’t Break appeared first on CSS-Tricks.

Source: css tricks

Categories
E-Commerce Invoicing and Accounting

20 Free Invoice Generators to Create Invoices Instantly

As a small business owner or a freelancer, you know the importance of invoicing. Invoices are sent to notify your clients about products and services you delivered, so you can get paid for your work….

Visit hongkiat.com for full content.
Source: hongkiat

Categories
Uncategorized

Differences Between Static Generated Sites And Server-Side Rendered Apps

Differences Between Static Generated Sites And Server-Side Rendered Apps

Differences Between Static Generated Sites And Server-Side Rendered Apps

Timi Omoyeni

2020-07-02T12:00:00+00:00
2020-07-05T00:11:03+00:00

JavaScript currently has three types of applications that you can build with: Single Page Applications (SPAs), pre-rendering/static generated sites and server-side rendered applications. SPAs come with many challenges, one of which is Search Engine Optimization (SEO). Possible solutions are to make use of Static Site Generators or Server-Side Rendering (SSR).

In this article, I’m going to explain them alongside listing their pros and cons so you have a balanced view. We’re going to look at what static generated/pre-rendering is as well as frameworks such as Gatsby and VuePress that help in creating statically generated sites. We’re also going to look at what server-side rendered (SSR) applications are as well as frameworks like Nextjs and Nuxtjs that can help you create SSR applications. Finally, we’re going to cover the differences between these two methods and which of them you should use when building your next application.

Note: You can find all the code snippets in this article on GitHub.

What Is A Static Site Generator?

A Static Site Generator (SSG) is a software application that creates HTML pages from templates or components and a given content source. You give it some text files and content, and the generator will give you back a complete website, and this completed website is referred to as a static generated site. What this means is that your site pages are generated at build time and your site content does not change unless you add new contents or components and “rebuild” or you have to rebuild your site if you want it to be updated with new content.

Diagram explaining how static site generation works

How static site generation works (Large preview)

This approach is good for building applications that the content does not change too often — sites that the content does not have to change depending on the user, and sites that do not have a lot of user-generated content. An example of such a site is a blog or a personal website. Let’s look at some advantages of using static generated sites.

PROS

  • Fast website: Since all of your site’s pages and content have been generated at build time, you do not have to worry about API calls to the server for content and this makes your site very fast.
  • Easy to deploy: After your static site has been generated, you would be left with static files, and hence, it can be easily deployed to platforms like Netlify.
  • Security: Static generated site are solely composed of static files, the risk of being vulnerable to cyber attacks is minimal. This is because static generated sites have no database, attackers cannot inject malicious code or exploit your database.
  • You can use version control software (e.g git) to manage and track changes to your content. This can come in handy when you want to roll back changes you made to the content on your site.

CONS

  • Content can become stale if it changes too quickly.
  • To update its content, you have to rebuild the site.
  • Build time would increase depending on the size of the application.

Examples of static site generators are GatsbyJS and VuePress. Let us take a look at how to create static sites using these two generators.

Gatsby

According to their official website,

“Gatsby is a free and open-source framework based on React that helps developers build blazing-fast websites and apps.”

This means developers familiar with React would find it easy to get started with Gatsby.

To use this generator, you first have to install it using NPM:

npm install -g gatsby-cli

This will install Gatsby globally on your machine, you only have to run this command once on your machine. After this installation is complete, you can create your first static site generator using the following command.

gatsby new demo-gatsby

This command will create a new Gatsby project that I have named demo-gatsby. When this is done, you can start up your app server by running the following command:

cd demo-gatsby
gatsby develop

Your Gatsby application should be running on localhost:8000.

Gatsby default landing page

Gatsby default starter page (Large preview)

The folder structure for this app looks like this;

--| gatsby-browser.js  
--| LICENSE        
--| README.md
--| gatsby-config.js
--| node_modules/  
--| src/
----| components
----| pages
----| images
--| gatsby-node.js     
--| package.json   
--| yarn.lock
--| gatsby-ssr.js      
--| public/
----| icons
----| page-data
----| static

For this tutorial, we’re only going to look at the src/pages folder. This folder contains files that would be generated into routes on your site.

To test this, let us add a new file (newPage.js) to this folder:

import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
const NewPage = () => (
  <Layout>
    <SEO title="My New Page" />
    <h1>Hello Gatsby</h1>
    <p>This is my first Gatsby Page</p>
    <button>
      <Link to='/'>Home</Link>
    </button>
  </Layout>
)
export default NewPage

Here, we import React from the react package so when your code is transpiled to pure JavaScript, references to React will appear there. We also import a Link component from gatsby and this is one of React’s route tag that is used in place of the native anchor tag ( <a href='#'>Link</a>). It accepts a to prop that takes a route as a value.

We import a Layout component that was added to your app by default. This component handles the layout of pages nested inside it. We also import the SEO component into this new file. This component accepts a title prop and configures this value as part of your page’s metadata. Finally, we export the function NewPage that returns a JSX containing your new page’s content.

And in your index.js file, add a link to this new page we just created:

import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => (
  <Layout>
    <SEO title="Home" />
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
      <Image />
    </div>
    <Link to="/page-2/">Go to page 2</Link>
    {/* new link */}
    <button>
      <Link to="/newPage/">Go to New Page</Link>
    </button>
  </Layout>
)
export default IndexPage

Here, we import the same components that were used in newPage.js file and they perform the same function in this file. We also import an Image component from our components folder. This component is added by default to your Gatsby application and it helps in lazy loading images and serving reduced file size. Finally, we export a function IndexPage that returns JSX containing our new link and some default content.

Now, if we open our browser, we should see our new link at the bottom of the page.

Gatsby default landing page with link to a new page

Gatsby landing page with new link (Large preview)

And if you click on Go To New Page, it should take you to your newly added page.

New page containing some texts

New gatsby page (Large preview)

VuePress

VuePress is a static site generator that is powered by Vue, Vue Router and Webpack. It requires little to no configuration for you to get started with it. While there are a number of tools that are static site generators, VuePress stands out from amongst the pack for a single reason: its primary directive is to make it easier for developers to create and maintain great documentation for their projects.

To use VuePress, you first have to install it:

//globally
yarn global add vuepress # OR npm install -g vuepress

//in an existing project
yarn add -D vuepress # OR npm install -D vuepress

Once the installation process is done, you can run the following command in your terminal:

# create the project folder
mkdir demo-vuepress && cd demo-vuepress

# create a markdown file
echo '# Hello VuePress' > README.md

# start writing
vuepress dev

Here, we create a folder for our VuePress application, add a README.md file with # Hello VuePress as the only content inside this file, and finally, start up our server.

When this is done, our application should be running on localhost:8080 and we should see this in our browser:

A VuePress webpage with a text saying ‘Hello VuePress’

VuePress landing page (Large preview)

VuePress supports VueJS syntax and markup inside this file. Update your README.md file with the following:

# Hello VuePress
_VuePress Rocks_
> **Yes!**
_It supports JavaScript interpolation code_
> **{{new Date()}}**
<p v-for="i of ['v','u', 'e', 'p', 'r', 'e', 's', 's']">{{i}}</p>

If you go back to your browser, your page should look like this:

Updated VuePress page

Updated Vuepress page (Large preview)

To add a new page to your VuePress site, you add a new markdown file to the root directory and name it whatever you want the route to be. In this case, I’ve gone ahead to name it Page-2.md and added the following to the file:

# hello World
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.

And now, if you navigate to /page-2 in your browser, we should see this:

A VuePress webpage containing hello world

A “Hello World” page in VuePress (Large preview)

What Is Server-Side Rendering? (SSR)

Server-Side Rendering (SSR), is the process of displaying web-pages on the server and passing it to the browser/client-side instead of rendering it in the browser. Server-side sends a fully rendered page to the client; the client’s JavaScript bundle takes over and allows the SPA framework to operate.

This means if you have an application that is server-side rendered, your content is fetched on the server side and passed to your browser to display to your user. With client-side rendering it is different, you would have to navigate to that page first before it fetches data from your server meaning your user would have to wait for some seconds before they’re served with the content on that page. Applications that have SSR enabled are called Server-side rendered applications.

A diagram explaining how server-side rendering works

How SSR works (Large preview)

This approach is good for building complex applications that require user interaction, rely on a database, or where the content changes very often. This is because content on these sites changes very often and the users need to see the updated content as soon as they’re updated. It is also good for applications that have tailored content depending on who is viewing it and applications where you need to store user-specific data like email and user preference while also catering for SEO. An example of this is a large e-commerce platform or a social media site. Let us look at some of the advantages of server-side rendering your applications.

Pros

  • Content is up to date because it fetches content on the go;
  • Your site loads fast because it fetches its content on the server-side before rendering it to the user;
  • Since in SSR JavaScript is rendered server-side, your users’ devices have little relevance to the load time of your page and this leads to better performance.

CONS

  • More API calls to the server since they’re made per request;
  • Cannot deploy to a static CDN.

Further examples of frameworks that offer SSR are Next.js and Nuxt.js.

Next.js

Next.js is a React.js framework that helps in building static sites, server-side rendered applications, and so on. Since it was built on React, knowledge of React is required to use this framework.

To create a Next.js app, you need to run the following:

npm init next-app
# or
yarn create next-app

You would be prompted to choose a name your application, I have named my application demo-next. The next option would be to select a template and I’ve selected the Default starter app after which it begins to set up your app. When this is done, we can now start our application

cd demo-next
yarn dev 
# or npm run dev

Your application should be running on localhost:3000 and you should see this in your browser;

Default Nextjs landing page

Next.js landing page (Large preview)

The page that is being rendered can be found in pages/index.js so if you open this file and modify the JSX inside the Home function, it would reflect in your browser. Replace the JSX with this:

import Head from 'next/head'
export default function Home() {
  return (
    <div className="container">
      <Head>
        <title>Hello Next.js</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1 className="title">
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>
        <p className='description'>Nextjs Rocks!</p>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        .title a {
          color: #0070f3;
          text-decoration: none;
        }
        .title a:hover,
        .title a:focus,
        .title a:active {
          text-decoration: underline;
        }
        .title {
          margin: 0;
          line-height: 1.15;
          font-size: 4rem;
        }
        .title,
        .description {
          text-align: center;
        }
        .description {
          line-height: 1.5;
          font-size: 1.5rem;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  )
}

In this file, we make use of Next.js Head component to set our page’s metadata title and favicon for this page. We also export a Home function that returns a JSX containing our page’s content. This JSX contains our Head component together with our main page’s content. It also contains two style tags, one for styling this page and the other for the global styling of the app.

Now, you should see that the content on your app has changed to this:

Nextjs landing page containing ‘welcome to Nextjs’ text

Updated landing page (Large preview)

Now if we want to add a new page to our app, we have to add a new file inside the /pages folder. Routes are automatically created based on the /pages folder structure, this means that if you have a folder structure that looks like this:

--| pages
----| index.js ==> '/'
----| about.js ==> '/about'
----| projects
------| next.js ==> '/projects/next'

So in your pages folder, add a new file and name it hello.js then add the following to it:

import Head from 'next/head'
export default function Hello() {
  return (
    <div>
       <Head>
        <title>Hello World</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className='container'>
        <h1 className='title'>
         Hello <a href="https://en.wikipedia.org/wiki/Hello_World_(film)">World</a>
        </h1>
        <p className='subtitle'>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem provident soluta, sit explicabo impedit nobis accusantium? Nihil beatae, accusamus modi assumenda, optio omnis aliquid nobis magnam facilis ipsam eum saepe!</p>
      </main>
      <style jsx> {`
      
      .container {
        margin: 0 auto;
        min-height: 100vh;
        max-width: 800px;
        text-align: center;
      }
      .title {
        font-family: "Quicksand", "Source Sans Pro", -apple-system, BlinkMacSystemFont,
          "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        display: block;
        font-weight: 300;
        font-size: 100px;
        color: #35495e;
        letter-spacing: 1px;
      }
      .subtitle {
        font-weight: 300;
        font-size: 22px;
        color: #526488;
        word-spacing: 5px;
        padding-bottom: 15px;
      }
      `} </style>
    </div>
  )
}

This page is identical to the landing page we already have, we only changed the content and added new styling to the JSX. Now if we visit localhost:3000/hello, we should see our new page:

A Nextjs webpage containing ‘Hello world’

A “Hello World ” page in Next.js (Large preview)

Finally, we need to add a link to this new page on our index.js page, and to do this, we make use of Next’s Link component. To do that, we have to import it first.

# index.js
import Link from 'next/link'

#Add this to your JSX
<Link href='/hello'>
<Link href='/hello'>
  <a>Next</a>
</Link>

This link component is how we add links to pages created in Next in our application.

Now if we go back to our homepage and click on this link, it would take us to our /hello page.

Nuxt.js

According to their official documentation:

“Nuxt is a progressive framework based on Vue.js to create modern web applications. It is based on Vue.js official libraries (vue, vue-router and vuex) and powerful development tools (webpack, Babel and PostCSS). Nuxt’s goal is to make web development powerful and performant with a great developer experience in mind.”

It is based on Vue.js so that means Vue.js developers would find it easy getting started with it and knowledge of Vue.js is required to use this framework.

To create a Nuxt.js app, you need to run the following command in your terminal:

yarn create nuxt-app <project-name>
# or npx
npx create-nuxt-app <project-name>

This would prompt you to select a name along with some other options. I named mine demo-nuxt and selected default options for the other options. When this is done, you can open your app folder and open pages/index.vue. Every file in this folder file is turned into a route and so our landing page is controlled by index.vue file. So if you update it with the following:

<template>
  <div class="container">
    <div>
      <logo />
      <h1 class="title">
        Hello Nuxt
      </h1>
      <h2 class="subtitle">
        Nuxt.js ROcks!
      </h2>
      <div class="links">
        <a
          href="https://nuxtjs.org/"
          target="_blank"
          class="button--green"
        >
          Documentation
        </a>
        <a
          href="https://github.com/nuxt/nuxt.js"
          target="_blank"
          class="button--grey"
        >
          GitHub
        </a>
      </div>
    </div>
  </div>
</template>
<script>
import Logo from '~/components/Logo.vue'
export default {
  components: {
    Logo
  }
}
</script>
<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 100px;
  color: #35495e;
  letter-spacing: 1px;
}
.subtitle {
  font-weight: 300;
  font-size: 42px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}
.links {
  padding-top: 15px;
}
</style>

And run your application:

cd demo-nuxt
# start your applicatio
yarn dev # or npm run dev

Your application should be running on localhost:3000 and you should see this:

Default Nuxtjs landing page

Nuxt.js landing page (Large preview)

We can see that this page displays the content we added in to index.vue. The router structure works the same way Next.js router works; it renders every file inside /pages folder into a page. So let us add a new page (hello.vue) to our application.

<template>
  <div>
    <h1>Hello World!</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id ipsa vitae tempora perferendis, voluptate a accusantium itaque vel ex, provident autem quod rem saepe ullam hic explicabo voluptas, libero distinctio?</p>
  </div>
</template>
<script>
export default {};
</script>
<style>
</style>

So if you open localhost:3000/hello, you should see your new page in your browser.

A Nuxtjs webpage containing ‘Hello World’

“Hello World” page in Nuxtjs (Large preview)

Taking A Closer Look At The Differences

Now that we have looked at both static-site generators and server-side rendering and how to get started with them by using some popular tools, let us look at the differences between them.

Static Sites Generators Server-Side Rendering
Can easily be deployed to a static CDN Cannot be deployed to a static CDN
Content and pages are generated at build time Content and pages are generated per request
Content can become stale quickly Content is always up to date
Fewer API calls since it only makes it at build time Makes API calls each time a new page is visited

Conclusion

We can see why it is so easy to think both static generated sites and server-side rendered applications are the same. Now that we know the differences between them are, I would advise that we try to learn more on how to build both static generated sites and server-side rendered applications in order to fully understand the differences between them.

Further Resources

Here are some useful links that are bound to help you get started in no time:

Smashing Editorial
(ks, ra, il)

Source: smash mag

Categories
Freelance Freelancers Invoicing and Accounting

Top 10 Invoicing & Accounting Tools For Freelancers

Freelancers usually handle many jobs at the same time and the client is not the only reason who drive a freelancer nuts. Being your own boss and manager means you are your own accountant as well….

Visit hongkiat.com for full content.
Source: hongkiat