Web Standards

Awards That Look Beyond the Flashy

Css Tricks - Thu, 10/03/2019 - 8:11am

Dan Mall is judging the Communication Arts Interactive 2020 awards. These types of things are usually a celebration of flashy, short-lived, one-off designs. Those things are awesome, but Dan has more in mind:

I’d love to award work that demonstrates creative use of the highest level of color contrast ratios and works well on assistive devices. I’d love to award work that’s still useful when JavaScript fails. I’d love to award work that shows smart thinking and strategy in addition to flawless execution and art direction. I’d love to award work that serves business and user needs.

Direct Link to ArticlePermalink

The post Awards That Look Beyond the Flashy appeared first on CSS-Tricks.

Adaptive Photo Layout with Flexbox

Css Tricks - Thu, 10/03/2019 - 4:24am

Let’s take a look at a super lightweight way to create a horizontal masonry effect for a set of arbitrarily-sized photos. Throw any set of photos at it, and they will line up edge-to-edge with no gaps anywhere.

The solution is not only lightweight but also quite simple. We’ll be using an unordered list of images and just 17 lines of CSS, with the heavy lifters being flexbox and object-fit.

Why?

I have two hobbies: documenting my life with photos, and figuring out interesting ways to combine CSS properties, both old and new.

A couple of weeks ago, I attended XOXO and shot a ton of photos which I narrowed down to a nice little set of 39. Wanting to own my content, I’ve spent the past couple of years thinking about putting together a simple photo blog, but was never able to nail the layout I had in mind: a simple masonry layout where photos fill out rows while respecting their aspect ratio (think Photos.app on iOS, Google Photos, Flickr…).

I did some research to see if there were any lightweight, non-JavaScript options, but couldn’t find anything suiting my needs. Facing some delayed flights, I started playing around with some code, limiting myself to keep things as simple as possible (because that’s my definition of fun).

Basic Markup

Since I’m basically creating a list of images, I opted for an unordered list:

<ul> <li> <img> </li> <!-- ... --> <li> <img> </li> </ul> All hail flexbox

Then came a string of lightbulb moments:

  • Flexbox is great for filling up rows by determining cell width based on cell content.
  • This meant the images (landscape or portrait) all needed to have the same height.
  • I could use object-fit: cover; to make sure the images filled the cells.

In theory, this sounded like a solid plan, and it got me a result I was about 90% happy with.

ul { display: flex; flex-wrap: wrap; } li { height: 40vh; flex-grow: 1; } img { max-height: 100%; min-width: 100%; object-fit: cover; vertical-align: bottom; }

Note: 40vh seemed like the best initial approach for desktop browsers, showing two full rows of photos at a reasonable size, and hinting at more below. This also allowed more photos per line, which dramatically improves the aspect ratios.

Last row stretchiness

The only issue I ran into is that flexbox really wants to fill all the lines, and it did some silly things to the aspect ratios of the photos on the last row. This is probably my least favorite bit of this layout, but I had to add an empty <li> element at the end of the list.

<ul> <li> <img> </li> <!-- ... --> <li> <img> </li> <li></li> </ul>

Combined with this bit of CSS:

li:last-child { flex-grow: 10; }

Note: There's no science in using "10" here. In all my testing, this delivered the best results.

Demo

See the Pen
Adaptive Photo Layout
by Tim Van Damme (@maxvoltar)
on CodePen.

Viewport optimization

There are some considerations to keep in mind when working in different viewport orientations.

Portrait

If your viewport is taller than it is wide, this approach limits the amount of photos per line thus messing up their aspect ratios. To solve this, you can make the photo rows less tall with this simple media query:

@media (max-aspect-ratio: 1/1) { li { height: 30vh; } } Short Screens

To help with small devices in landscape, increasing the height of photos helps to see them as large as possible:

@media (max-height: 480px) { li { height: 80vh; } } Smaller Screens + Portrait

Most phones aren’t wide enough to allow flexbox to properly do its job without miniaturizing the photos, so here I opted to not try to fit multiple photos per line. Still, it’s worth setting a maximum height here so you’ll at least have a hint at the next photo in the list.

@media (max-aspect-ratio: 1/1) and (max-width: 480px) { ul { flex-direction: row; } li { height: auto; width: 100%; } img { width: 100%; max-height: 75vh; min-width: 0; } } There we have it!

This approach doesn’t fully respect the aspect ratios of photos (but it’s close) and occasionally leads to some weird results, but I absolutely love the simplicity and flexibility of it all. Want to have your gallery scroll horizontally instead of vertically? A couple of tweaks will allow you to do this. Are there 1,000 photos in the gallery or just one? It’ll all look good. Unclear about aspect ratios? Flexbox is your best friend. Take another look at the demo if you haven't yet, and let me know what you think!

Bonus

Depending on the size of these photos, a page like this can grow to multiple megabytes real quick. On the blog I’m working on, I’ve added loading="lazy" to help with this. With that attribute in place on the images, it only loads photos once you approach them while scrolling. It’s supported just in Chrome for now, but you could roll your own more supported technique.

The post Adaptive Photo Layout with Flexbox appeared first on CSS-Tricks.

Automated (and Guided!) Accessibility Audits with axe Pro

Css Tricks - Thu, 10/03/2019 - 4:24am

It's important to know there are tools for automated accessibility testing of websites. They are a vital part in helping make sure your website is usable for everyone, which is both a noble goal and damn good for business. Automated tests won't catch every potential accessibility issue, but they help a great deal, and in my experience, help establish a culture of caring about accessibility. The more seriously you take these tests and actually fix the problems, the more likely it is you're doing a good job of accessibility overall.

There is one testing tool that stands above the rest, axe (it's even what Google's Lighthouse uses), and now it's gotten a whole lot better with axe Pro.

The axe extention is still the powerhouse, where robust accessibility reports are a click away in DevTools:

But there's more!

Guided Question-Answer Accessibility Walkthroughs

Not to bury the lede, this is probably the best new feature of axe Pro. The tool is so friendly, it gives accessibility testing powers to just about anybody:

“Axe Pro essentially lets every developer function as an in-house accessibility expert,” says Preety Kumar, CEO of Deque Systems.

Run the tests, and it just asks you stuff in plain English.

Anybody can answer questions from a guided tour like this. It's extremely helpful to be hand-held through thinking about these important aspects of your site.

For example, here's a test walkthrough of it helping me think about header and header levels:

First, you identify the problems, then you can save the information so you can work on the fixes as you can.

Your tests can be saved as online reports

Working in DevTools is nice and the perfect place to be digging into the accessibility issues on your site. But that session in DevTools is short-lived! It's just one developer working on one computer at one point in time. With the new axe Pro web dashboard, you can save your tests online. This is useful for a variety of reasons:

  • You can save your testing so far and come back to it later to keep going.
  • You can clear out tests and re-do them, to track your progress moving forward.
  • You can have multiple tests on the dashboard to help you test multiple pages and projects.
  • Your team has a home to manage these tests all together.
You can export the data

If you'd prefer to get the results out of axe and somewhere else, you can now export the data as JSON or CSV. Perhaps you want to track the results over time to visualize improvements or port the information to some other tool. The data is yours.

I found helpful prompts immediately.

I'd like to think I care about accessibility and work accessibily as I go, but if you're anything like me, you'll find mistakes find their way into your code bases over time. Just like we might have automated tools to watch our performance metrics over time, we can and should be regularly testing accessibility, especially when automation helpfulness like axe Pro provides.

Just in playing with axe Pro for a few hours, I've...

  • Found many images that had missing and incorrect alt text on them.
  • Found a few elements that were using header tags that really shouldn't have been.
  • Fixed some color contrast on some elements that were just barely not AA and light tweaks got them there.

That second one I found very satisfying as the guided tour helped me find them. That's something an entirely automated tool won't really help find, it requires you looking at things and making judgment calls.

I'm very optimistic this is going to help lots of folks unearth accessibility issues they wouldn't have caught otherwise.

It's free for a limited time

It's kind of a big deal:

Developers can typically identify about half of all critical accessibility blockers through axe.

You might as well try it out!

The post Automated (and Guided!) Accessibility Audits with axe Pro appeared first on CSS-Tricks.

Mina Markham Should Make Beyoncé’s Site Accessible

Css Tricks - Thu, 10/03/2019 - 4:24am

I remember when this went around in January, and I'm a little shocked it didn't happen.

Mina is the perfect person for the job (like, duh) and the result would be good for everyone. Let's make this happen. The least we can do is sign Amélie Lamont's petition.

Direct Link to ArticlePermalink

The post Mina Markham Should Make Beyoncé’s Site Accessible appeared first on CSS-Tricks.

Demonstrating Reusable React Components in a Form

Css Tricks - Wed, 10/02/2019 - 4:14am

Components are the building blocks of React applications. It’s almost impossible to build a React application and not make use of components. It’s widespread to the point that some third-party packages provide you with components you can use to integrate functionality into your application.

These third-party components tend to be reusable. The difference between them and components you probably have in your application has to do with specificity.

Here’s what I mean. Say you run a company that sells polo shirts. There are two things you can do:

  1. You can produce polos that already have a design on them, or
  2. You can have the buyer choose the design they want.

Some fundamental things will be consistent, like all polos should be short-sleeved. But the user can pick variations of the shirts, such as the color and size. A short-sleeve polo would make a good React component in that case: it’s the same item with different variations.

Now let’s say you’re working on a login form. Like polo shirts, the form has consistent characteristics, but instead of size and color variations, we'd be looking at input fields, a submit button, perhaps even a lost password link. This can be componentized and implemented with variations in the inputs, buttons, links, etc.

Input Element Example

Let’s look at it from the perspective of creating an input field for your form. Here is how a typical text input will look like as a React component:

class Form extends React.Component { this.state = { username: '' } handleChange = (event) => { this.setSate({ username: event.target.value }) } render() { return ( <input name="username type={type} placeholder="Enter username" onChange={this.handleChange} value={this.state.username} /> ) } }

To make this input element reusable in other places and projects, we’ll have to extract it into its own component. Let’s call it FormInput.

const FormInput = ({ name, type, placeholder, onChange, className, value, error, children, label, ...props }) => { return ( <React.Fragment> <label htmlFor={name}>{label}</label> <input name={name} type={type} placeholder={placeholder} onChange={onChange} value={value} className={className} style={error && {border: 'solid 1px red'}} /> { error && <p>{ error }</p>} </React.Fragment> ) } FormInput.defaultProps = { type: "text", className: "" } FormInput.propTypes = { name: PropTypes.string.isRequired, type: PropTypes.string, placeholder: PropTypes.string.isRequired, type: PropTypes.oneOf(['text', 'number', 'password']), className: PropTypes.string, value: PropTypes.any, onChange: PropTypes.func.isRequired }

The component accepts certain props, such as the attributes that we need to make the input with valid markup, including the placeholder, value and name. We set up the input element in the render function, setting the attribute values as the props that are passed to the component. We even bind the input to a label to ensure they’re always together. You can see that we’re not making assumptions by predefining anything. The idea is to ensure that the component can be used in as many scenarios as possible.

This makes for a good component because it enforces good markup (something Brad Frost calls dumb React) which goes to show that not every component has to be some highly complex piece of functionality. Then again, if we were talking about something super basic, say a static heading, then reaching for a React component might be overkill. The possible yardstick for making something a reusable component probably ought to be when you need the same functionality in other parts of an application. There’s generally no need for a "reusable" component if that component is only used once.

We can make use of our input component in another component, the LoginPage.

class LoginPage extends React.Component { state = { user: { username: "", password: "" }, errors: {}, submitted: false }; handleChange = event => { const { user } = this.state; user[event.target.name] = event.target.value; this.setState({ user }); }; onSubmit = () => { const { user: { username, password } } = this.state; let err = {}; if (!username) { err.username = "Enter your username!"; } if (password.length < 8) { err.password = "Password must be at least 8 characters!"; } this.setState({ errors: err }, () => { if (Object.getOwnPropertyNames(this.state.errors).length === 0) { this.setState({ submitted: true }); } }); }; render() { const { submitted, errors, user: { username, password } } = this.state; return ( <React.Fragment> {submitted ? ( <p>Welcome onboard, {username}!</p> ) : ( <React.Fragment> <h3>Login!</h3> <FormInput label="Username" name="username" type="text" value={username} onChange={this.handleChange} placeholder="Enter username..." error={errors.username} required className="input" /> <FormInput label="Password" name="password" type="password" value={password} onChange={this.handleChange} placeholder="Enter password..." error={errors.password} className="input" required /> <Button type="submit" label="Submit" className="button" handleClick={this.onSubmit} /> </React.Fragment> )} </React.Fragment> ); } }

See how LoginPage uses the FormInput twice? We’re using it both as the text input for a username and another text input for a password. If we want to make any changes to how the input functions, we can make those changes inside the FormInput component file we created and they will be applied to every instance where the input component is used. That’s the fundamental upside to having reusable components: you don’t have to repeat yourself.

Even the errors are displayed from the FormInput component.

The onSubmit function first validates the user object which we get from the form, ensuring that it fits the structure that there is a value for username. Notice that we can even extend the input’s functionality, like we did to check that the password contains at least eight characters.

If you look at the code, you’ll see a have a Button component in there. That’s not the same as a HTML <button> element, but instead another component that takes the props that define the type of button we want (submit, reset, button), its class name, what to do on click, and the label. There are lots of other button attributes we could integrate to enforce whatever standard is needed.

const Button = (props) => ( <button type={props.type} className={props.className} onClick={props.handleClick} > {props.label} </button> )

Here’s our final login form when all of our components are put together.

See the Pen
Reusable Button Component
by Kingsley Silas Chijioke (@kinsomicrote)
on CodePen.

Wanna give this a try yourself? Try working on a reusable <select> element. If that’s too difficult, you can start with a <textarea> element, then perhaps a checkbox before hopping over to <select>. The key idea is to make it generic. I’ll like to see what you came up with, so link up your work in the comment section!

The post Demonstrating Reusable React Components in a Form appeared first on CSS-Tricks.

Zero hands up.

Css Tricks - Wed, 10/02/2019 - 4:13am

Asked an entire room full of webdevs yesterday if any of them knew that FF/Chrome/Opera/Brave/etc. for iOS weren't allowed to compete on engine quality.

Zero hands up.

— Alex Russell (@slightlylate) September 25, 2019

It's worth making this clear then. On iOS, the only browser engine is WebKit. There are other browsers, but they can't bring their own engine (Blink/Gecko). So, if you're using Chrome or Firefox on iOS, it's really the same engine Safari is using, only slightly less capable (e.g. no third-party content blocker apps work in them).

It's worth knowing that as a developer. While Chrome supports stuff like service workers on their desktop browser and on other platforms, the browser engine made available to non-Safari browsers on iOS does not. You don't have them there. Likewise for Firefox.

The post Zero hands up. appeared first on CSS-Tricks.

The Many Ways to Link Up Shapes and Images with HTML and CSS

Css Tricks - Tue, 10/01/2019 - 4:20am

Different website designs often call for a shape other than a square or rectangle to respond to a click event. Perhaps your site has some kind of tilted or curved banner where the click area would be awkwardly large as a straight rectangle. Or you have a large uniquely shaped logo where you only want that unique shape to be clickable. Or you have an interactive image that responds differently when different regions of it are clicked.

You can surround those assets with an un-styled <a> tag to get a clickable rectangle that's approximately the right size. However, you can also control the shape of that region with different techniques, making sure the target for your click area exactly matches what’s visible on the screen.

SVG shapes

If your click target is an image or a portion of an image, and you have the ability to choose SVG as its format, you already have a great deal of control over how that element will behave on your page. The simplest way to make a portion of an SVG clickable is to add an an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one. In this example the link for the bullseye wraps a single circle element, but the more complex arrow shape is made up of two polygons and a path element.

See the Pen
target svg
by Bailey Jones (@bailey_jones)
on CodePen.

Note that I’ve used the deprecated xlink:href property in this demo to ensure that the link will work on Safari. The href alone would have worked in Internet Explorer, Chrome, and Firefox.

The only trick here is to make sure the <a> tag is inside the SVG markup and that the tag wraps the shape you want to be clickable. The viewbox for this SVG is still a rectangle, so wrapping the entire SVG element wouldn't have the same effect.

Image maps

Let’s say you don’t have control over the SVG markup, or that you need to add a clickable area to a raster image instead. It’s possible to apply a clickable target to a portion of an <img> tag using an image map.

Image maps are defined separately from the image source. The map will effectively overlay the entire image element, but it's up to you to define the clickable area. Unlike the hyperlink element in the SVG example, the coordinates in the image map don’t have anything to do with the definition of the source image. Image maps have been around since HTML 3, meaning they have excellent browser support. However, they can’t be styled with CSS alone to provide interactive cues, like we were able to do with SVG on hover — the cursor is the only visual indicator that the target area of the image can be clicked. There are, however, options for styling the areas with JavaScript.

W3 Schools has an excellent example of an image map using a picture of the solar system where the sun and planets are linked to close-up images of those targets — everywhere else in the image is un-clickable. That’s because the coordinates of the areas defined in their image map match the locations of the sun and planets in the base image.

Here’s another example from Derek Fogge that uses uses maps to create more interesting click targets. It does use jQuery to style the areas on click, but notice the way a map overlays the image and coordinates are used to create the targets.

See the Pen
responsive image map demo
by Derek Fogge (@PositionRelativ)
on CodePen.

You can implement image maps on even more complex shapes too. In fact, let’s go back to the same target shape from the SVG example but using a raster image instead. We still want to link up the arrow and the bullseye but this time do not have SVG elements to help us out. For the bullseye, we know the X and Y coordinates and its radius in the underlying image, so it’s fairly easy to define a circle for the region. The arrow shape is more complicated. I used https://www.image-map.net to plot out the shape and generate the area for the image map — it’s made up of one polygon and one circle for the rounded edge at the top.

See the Pen
target image map
by Bailey Jones (@bailey_jones)
on CodePen.

Clip-path

What if you want to use CSS to define the shape of a custom click region without resorting to JavaScript for the styling? The CSS clip-path property provides considerable flexibility for defining and styling target areas on any HTML element.

Here we have a click area in the shape of a five-pointed star. The star is technically a polygon, so we could use a star-shaped base image and an image map with corresponding coordinates like we did in the previous image map example. However, let’s put clip-path to use. The following example shows the same clip-path applied to both a JPG image and an absolutely positioned hyperlink element.

See the Pen
Clip-path
by Bailey Jones (@bailey_jones)
on CodePen.

Browser support for clip-path has gotten much better, but it can still be inconsistent for some values. Be sure to check support and vendor prefixes before relying on it.

We can also mix and match different approaches depending on what best suits the shape of a particular click target. Here, I’ve combined the "close" shape using Bennet Freely’s clippy with an SVG hyperlink element to build the start of a clickable tic-tac-toe game. SVG is useful here to make sure the "hole" in the middle of the "O" shape isn’t clickable. For the "X" though, which is a polygon, a single clip-path can style it.

See the Pen
tic tac toe
by Bailey Jones (@bailey_jones)
on CodePen.

Again, beware of browser support especially when mixing and matching techniques. The demo above will not be supported everywhere.

CSS shapes without transparent borders

The clip-path property allowed us to apply a predefined shape to an HTML element of our choice, including hyperlink elements. There are plenty of other options for creating elements HTML and CSS that aren’t squares and rectangles — you can see some of them in The Shapes of CSS. However, not all techniques will effect the shape of the click area as you might expect. Most of the examples in the Shapes of CSS rely on transparent borders, which the DOM will still recognize as part of your click target even if your users can’t see them. Other tricks like positioning, transform, and pseudo elements like ::before and ::after will keep your styled hyperlink aligned with its visible shape.

Here’s a CSS heart shape that does not rely on transparent borders. You can see how the the red heart shape is the only clickable area of the element.

See the Pen
Clickable heart
by Bailey Jones (@bailey_jones)
on CodePen.

Here’s another example that creates a CSS triangle shape using transparent borders. You can see how the click area winds up being outside the actual shape. Hover over the element and you’ll be able to see the true size of the click area.

See the Pen
clickable triangle
by Bailey Jones (@bailey_jones)
on CodePen.

Hopefully this gives you a good baseline understanding of the many ways to create clickable regions on images and shapes, relying on HTML and CSS alone. You may find that it’s necessary to reach for JavaScript in order to get a more advanced interactive experience. However, the combined powers of HTML, CSS, and SVG provide considerable options for controlling the precise shape of your click target.

The post The Many Ways to Link Up Shapes and Images with HTML and CSS appeared first on CSS-Tricks.

Enhancing The Clickable Area Size

Css Tricks - Tue, 10/01/2019 - 4:20am

Here’s a great post by Ahmad Shadeed on making sure that clickable areas in our interfaces are, well, clickable. He writes about making sure that links, buttons and other elements meet accessibility standards for both touch and mouse, too.

I particularly like the section where Ahmad writes about making a fake circle around an element and where he shows this example:

On a similar note, Andy Bell just wrote up a few notes about creating a semantic “breakout” button to make an entire element clickable. This is a common pattern where you might want a design element that looks like a card but the whole thing is effectively a single button. There are a few accessibility tips that Andy brings up that are very much worth taking a look at!

The same sort of thing might be said about buttons. Using a rounded border-radius trims the corners, creating small un-clickable areas.

Direct Link to ArticlePermalink

The post Enhancing The Clickable Area Size appeared first on CSS-Tricks.

Multi-Million Dollar HTML

Css Tricks - Mon, 09/30/2019 - 9:40am

Two stories:

  • Jason Grigsby finds Chipotle's online ordering form makes use of an input-masking technique that chops up a credit card expiration year making it invalid and thus denying the order. If pattern="\d\d" maxlength="2" was used instead (native browser feature), the browser is smart enough to do the right thing and not deny the order. Scratchpad math, based on published data, makes that worth $4.4 million dollars.
  • Adrian Roselli recalls an all-too-common form accessibility fail of missing a for/id attribute on labels and inputs results in an unusable experience and a scratchpad math loss of $18 million dollars to campaigns.

The label/input attribution thing really gets me. I feel like that's an extremely basic bit of HTML knowledge that benefits both accessibility and general UX. It's part of every HTML curriculum I've ever seen, and regularly pointed at as something you need to get right. And never a week goes by I don't find some production website not doing it.

We can do this everyone!

<label for="name">Name:</label> <input id="name" name="name" type="text"> <!-- or --> <label> Name: <input name="name" type="text"> </label>

The post Multi-Million Dollar HTML appeared first on CSS-Tricks.

How I Learned to Stop Worrying and Love Git Hooks

Css Tricks - Mon, 09/30/2019 - 5:41am

The merits of Git as a version control system are difficult to contest, but while Git will do a superb job in keeping track of the commits you and your teammates have made to a repository, it will not, in itself, guarantee the quality of those commits. Git will not stop you from committing code with linting errors in it, nor will it stop you from writing commit messages that convey no information whatsoever about the nature of the commits themselves, and it will, most certainly, not stop you from committing poorly formatted code.

Fortunately, with the help of Git hooks, we can rectify this state of affairs with only a few lines of code. In this tutorial, I will walk you through how to implement Git hooks that will only let you make a commit provided that it meets all the conditions that have been set for what constitutes an acceptable commit. If it does not meet one or more of those conditions, an error message will be shown that contains information about what needs to be done for the commit to pass the checks. In this way, we can keep the commit histories of our code bases neat and tidy, and in doing so make the lives of our teammates, and not to mention our future selves, a great deal easier and more pleasant.

As an added bonus, we will also see to it that code that passes all the tests is formatted before it gets committed. What is not to like about this proposition? Alright, let us get cracking.

Prerequisites

In order to be able to follow this tutorial, you should have a basic grasp of Node.js, npm and Git. If you have never heard of something called package.json and git commit -m [message] sounds like code for something super-duper secret, then I recommend that you pay this and this website a visit before you continue reading.

Our plan of action

First off, we are going to install the dependencies that make implementing pre-commit hooks a walk in the park. Once we have our toolbox, we are going to set up three checks that our commit will have to pass before it is made:

  • The code should be free from linting errors.
  • Any related unit tests should pass.
  • The commit message should adhere to a pre-determined format.

Then, if the commit passes all of the above checks, the code should be formatted before it is committed. An important thing to note is that these checks will only be run on files that have been staged for commit. This is a good thing, because if this were not the case, linting the whole code base and running all the unit tests would add quite an overhead time-wise.

In this tutorial, we will implement the checks discussed above for some front-end boilerplate that uses TypeScript and then Jest for the unit tests and Prettier for the code formatting. The procedure for implementing pre-commit hooks is the same regardless of the stack you are using, so by all means, do not feel compelled to jump on the TypeScript train just because I am riding it; and if you prefer Mocha to Jest, then do your unit tests with Mocha.

Installing the dependencies

First off, we are going to install Husky, which is the package that lets us do whatever checks we see fit before the commit is made. At the root of your project, run:

npm i husky --save-dev

However, as previously discussed, we only want to run the checks on files that have been staged for commit, and for this to be possible, we need to install another package, namely lint-staged:

npm i lint-staged --save-dev

Last, but not least, we are going to install commitlint, which will let us enforce a particular format for our commit messages. I have opted for one of their pre-packaged formats, namely the conventional one, since I think it encourages commit messages that are simple yet to the point. You can read more about it here.

npm install @commitlint/{config-conventional,cli} --save-dev ## If you are on a device that is running windows npm install @commitlint/config-conventional @commitlint/cli --save-dev

After the commitlint packages have been installed, you need to create a config that tells commitlint to use the conventional format. You can do this from your terminal using the command below:

echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js

Great! Now we can move on to the fun part, which is to say implementing our checks!

Implementing our pre-commit hooks

Below is an overview of the scripts that I have in the package.json of my boilerplate project. We are going to run two of these scripts out of the box before a commit is made, namely the lint and prettier scripts. You are probably asking yourself why we will not run the test script as well, since we are going to implement a check that makes sure any related unit tests pass. The answer is that you have to be a little bit more specific with Jest if you do not want all unit tests to run when a commit is made.

"scripts": { "start": "webpack-dev-server --config ./webpack.dev.js --mode development", "build": "webpack --config ./webpack.prod.js --mode production", "test": "jest", "lint": "tsc --noEmit", "prettier": "prettier --single-quote --print-width 80 "./**/*.{js,ts}" --write" }

As you can tell from the code we added to the package.json file below, creating the pre-commit hooks for the lint and prettier scripts does not get more complicated than telling Husky that before a commit is made, lint-staged needs to be run. Then you tell lint-staged to run the lint and prettier scripts on all staged JavaScript and TypeScript files, and that is it!

"scripts": { "start": "webpack-dev-server --config ./webpack.dev.js --mode development", "build": "webpack --config ./webpack.prod.js --mode production", "test": "jest", "lint": "tsc --noEmit", "prettier": "prettier --single-quote --print-width 80 "./**/*.{js,ts}" --write" }, "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "./**/*.{ts}": [ "npm run lint", "npm run prettier" ] }

At this point, if you set out to anger the TypeScript compiler by passing a string to a function that expects a number and then try to commit this code, our lint check will stop your commit in its tracks and tell you about the error and where to find it. This way, you can correct the error of your ways, and while I think that, in itself, is pretty powerful, we are not done yet!

By adding "jest --bail --coverage --findRelatedTests" to our configuration for lint-staged, we also make sure that the commit will not be made if any related unit tests do not pass. Coupled with the lint check, this is the code equivalent of wearing two safety harnesses while fixing broken tiles on your roof.

What about making sure that all commit messages adhere to the commitlint conventional format? Commit messages are not files, so we can not handle them with lint-staged, since lint-staged only works its magic on files staged for commit. Instead, we have to return to our configuration for Husky and add another hook, in which case our package.json will look like so:

"scripts": { "start": "webpack-dev-server --config ./webpack.dev.js --mode development", "build": "webpack --config ./webpack.prod.js --mode production", "test": "jest", "lint": "tsc --noEmit", "prettier": "prettier --single-quote --print-width 80 "./**/*.{js,ts}" --write" }, "husky": { "hooks": { "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", //Our new hook! "pre-commit": "lint-staged" } }, "lint-staged": { "./**/*.{ts}": [ "npm run lint", "jest --bail --coverage --findRelatedTests", "npm run prettier" ] }

If your commit message does not follow the commitlint conventional format, you will not be able to make your commit: so long, poorly formatted and obscure commit messages!

If you get your house in order and write some code that passes both the linting and unit test checks, and your commit message is properly formatted, lint-staged will run the Prettier script on the files staged for commit before the commit is made, which feels like the icing on the cake. At this point, I think we can feel pretty good about ourselves; a bit smug even.

Implementing pre-commit hooks is not more difficult than that, but the gains of doing so are tremendous. While I am always skeptical of adding yet another step to my workflow, using pre-commit hooks has saved me a world of bother, and I would never go back to making my commits in the dark, if I am allowed to end this tutorial on a somewhat pseudo-poetical note.

The post How I Learned to Stop Worrying and Love Git Hooks appeared first on CSS-Tricks.

Preloading Pages Just Before They are Needed

Css Tricks - Fri, 09/27/2019 - 11:08am

The typical journey for a person browsing a website: view a page, click a link, browser loads new page. That's assuming no funny business like a Single Page App, which still follows that journey, but the browser doesn't load a new page — the client fakes it for the sake of a snappier transition.

What if you could load that new page before the person clicks the link so that, when they do, the loading of that next page is much faster? There are two notable projects that try to help with that:

  • quicklink: detects visible links, waits for the browser to be idle and if it isn't on slow connection, it prefetches those links.
  • instant.page: if you hover over a link for 65ms, it preloads that link. The new Version 2 allows you to configure of the time delay or whether to wait for a click or press before preloading.

Combine those things with technological improvements like paint holding, and building a SPA architecture just for the speed benefits may become unnecessary (though it may still be desirable for other reasons, like code-splitting, putting the onus of routing onto front-end developers, etc.).

The post Preloading Pages Just Before They are Needed appeared first on CSS-Tricks.

A Codebase and a Community

Css Tricks - Fri, 09/27/2019 - 4:09am

I woke up one morning and realized that I had it all wrong. I discovered that code and design are unable to solve every problem on a design systems team, even if many problems can be solved by coding and designing in a dark room all day. Wait, huh? How on earth does that make any sense? Well, that’s because good design systems work is about hiring, too.

Let me explain.

First, let’s take a look at some common design systems issues. One might be that your components are a thick div soup which is causing issues for users and is all-round bad for accessibility. Another issue might be that you have a large number of custom components that are fragile and extremely difficult to use. Or maybe you have eight different illustration styles and four different modal components. Maybe you have a thousand different color values that are used inconsistently.

Everyone in an organization can typically feel these problems but they’re really hard to describe. Folks can see that it takes way longer to build things than it should and miscommunication is rampant. Our web app might have bad web performance, major accessibility issues and wildly inconsistent design. But why is this? What’s the root cause of all these dang problems?

The strange thing about design systems is it’s difficult to see what the root cause of all these inconsistencies and issues might be. And even the answer isn’t always entirely obvious once you see the problem.

A design systems team can write component documentation to fix these issues, or perhaps refactor things, audit patterns, refactor even more things, redesign components, and provide training and guidance. But when apps get to a certain size then one person (or even a whole team of people) tackling these problems isn’t enough to solve them.

Sure a design systems team can spend a whole bunch of time helping fix an issue but is that really the best use of their time? What if they convinced another team in the company to instead hire a dedicated front-end engineer to build a sustainable working environment? What if they hired an illustrator to make things consistent and ensure high quality across the entire app?

This is why design systems work is also about hiring.

A design systems team is in the perfect place to provide guidance around hiring because they’ll be the first to spot issues across an organization. They’ll see how components are being hacked together or where there’s too many unnecessary custom components that are not part of a library or style guide. The design systems team will see weaknesses in the codebase that no one else can see and they can show which teams are missing which particular skill sets — and fix that issue by hiring folks with skills in those specific areas.

If you're in management and don’t see all those inconsistencies every day, then it’s likely nothing will get done about it. We're unlikely to fix the issues we cannot see.

So as design systems folks, we ultimately need to care about hiring because of this: a codebase is a neighborhood and a community.

And the only way we can fix the codebase is by fixing the community.

The post A Codebase and a Community appeared first on CSS-Tricks.

What happens when you open a new install of browsers for the 1st time?

Css Tricks - Fri, 09/27/2019 - 4:09am

Interesting research from Jonathan Sampson, where he watches the network requests a browser makes the very first time you launch it on a fresh install, and otherwise do nothing. This gives you a little insight into what kind of information that browser wants to collect and disseminate.

This was all shared as tweets, but I'm linking to an unrolled thread if there's one available:

Looks like Brave is the cleanest and the most questionable is... Opera?

Direct Link to ArticlePermalink

The post What happens when you open a new install of browsers for the 1st time? appeared first on CSS-Tricks.

Weekly Platform News: Layout Shifts, Stalled High-Bitrate Videos, Screenshots in Firefox

Css Tricks - Thu, 09/26/2019 - 9:33am

In this week's roundup: fighting shifty layouts, some videos might be a bit stalled, and a new way to take screenshots in Firefox.

Let's get into the news!

Identifying the causes of layout shifts during page load

You can now use WebPageTest to capture any layout shifts that occur on your website during page load, and identify what caused them.

Step 1: Paste a snippet

Paste the following snippet into the “Custom Metrics” on webpagetest.org in field in the Custom tab (under Advanced Settings) and make sure that a Chrome browser is selected.

[LayoutShifts] return new Promise(resolve => { new PerformanceObserver(list => { resolve(JSON.stringify(list.getEntries().filter(entry => !entry.hadRecentInput))); }).observe({type: "layout-shift", buffered: true}); }); Step 2: Inspect entries

After completing the test, inspect the captured LayoutShifts entries on the Custom Metrics page, which is linked from the Details section.

Step 3: Check the filmstrip

Based on the "startTime" and "value" numbers in the data, use WebPageTest’s filmstrip view to pinpoint the individual layout shifts and identify their causes.

(via Rick Viscomi)

A high bitrate can cause your videos to stall

If you serve videos for your website from your own web server, keep an eye on the video bitrate (the author suggests FFmpeg and streamclarity.com). If your video has a bitrate of over 1.5 Mbps, playback may stall one or more times for people on 3G connections, depending on the video’s length.

50% of videos in this study have a bitrate that is greater than the downlink speed of a 3G connection — meaning that video playback will be delayed and contain stalls.

(via Doug Sillars)

Firefox’s :screenshot command

Firefox’s DevTools console includes a powerful command for capturing screenshots of the current web page. Like in Chrome DevTools, you can capture a screenshot of an individual element, the current viewport, or the full page, but Firefox’s :screenshot command also provides advanced options for adjusting the device pixel ratio and setting a delay.

// capture a full-page screenshot at a device pixel ratio of 2 :screenshot --fullpage --dpr 2 // capture a screenshot of the viewport with a 5-second delay :screenshot --delay 5

(via Reddit)

Read even more news in my weekly Sunday issue, which can be delivered to you via email every Monday morning.

Web Platform News: Sunday issue ?

The post Weekly Platform News: Layout Shifts, Stalled High-Bitrate Videos, Screenshots in Firefox appeared first on CSS-Tricks.

Meeting GraphQL at a Cocktail Mixer

Css Tricks - Thu, 09/26/2019 - 4:15am

GraphQL and REST are two specifications used when building APIs for websites to use. REST defines a series of unique identifiers (URLs) that applications use to request and send data. GraphQL defines a query language that allows client applications to specify precisely the data they need from a single endpoint. They are related technologies and used for largely the same things (in fact, they can and often do co-exist), but they are also very different.

That’s a little dry, eh? Let’s explain it a much more entertaining way that might help you understand better, and maybe just get you a little excited about GraphQL!

&#x1f379; You’re at a cocktail mixer

You’re attending this mixer to help build your professional network, so naturally, you want to collect some data about the people around you. Close by, there are five other attendees.

Their name tags read:

  • Richy REST
  • Friend of Richy REST
  • Employer of Richy REST
  • Georgia GraphQL

Being the dynamic, social, outgoing animal that you are, you walk right up to Richy REST and say, "Hi, I’m Adam Application, who are you?" Richy REST responds:

{ name: "Richy REST", age: 33, married: false, hometown: "Circuits-ville", employed: true // ... 20 other things about Richy REST }

"Whoa, that was a lot to take in," you think to yourself. In an attempt to avoid any awkward silence, you remember Richy REST specifying that he was employed and ask, "Where do you work?"

Strangely, Richy REST has no idea where he works. Maybe the Employer of Richy Rest does?

You ask the same question to the Employer of Richy REST, who is delighted to answer your inquiry! He responds like so:

{ company: "Mega Corp", employee_count: 11230, head_quarters: "1 Main Avenue, Big City, 10001, PL" year_founded: 2005, revenue: 100000000, // ... 20 other things about Richy REST Employer }

At this point, you’re exhausted. You don’t even want to meet the Friend of Richy Rest! That might take forever, use up all your energy and, you don’t have the time.

However, Georgia GraphQL has been standing there politely, so you decide to engage her.

"Hi, what’s your name?"

{ name: "Georgia GraphQL" }

"Where are you from, and how old are you?"*

{ hometown: "Pleasant-Ville", age: 28 }

"How many hobbies and friends do you have and what are your friends' names?"

{ hobbies_count: 12, friends_count: 50, friends: [ { name: "Steve" }, { name: "Anjalla" }, // ...etc ] }

Georgia GraphQL is incredible, articulate, concise, and to the point. You 100% want to swap business cards and work together on future projects with Georgia.

This anecdote encapsulates the developer's experience of working with GraphQL over REST. GraphQL allows developers to articulate what they want with a tidy query and, in response, only receive what they specified. Those queries are fully dynamic, so only a single endpoint is required. REST, on the other hand, has predefined responses and often requires applications to utilize multiple endpoints to satisfy a full data requirement.

Metaphor over! Let’s talk brass tacks.

To expand further upon essential concepts presented in the cocktail mixer metaphor let’s specifically address two limitations that often surface when using REST.

1. Several trips when fetching related resources

Data-driven mobile and web applications often require related resources and data sets. Thus, retrieving data using a REST API can entail multiple requests to numerous endpoints. For instance, requesting a Post entity and related Author might be completed by two requests to different endpoints:

someServer.com/authors/:id someServer.com/posts/:id

Multiple trips to an API impacts the performance and readiness of an application. It is also a more significant issue for low bandwidth devices (e.g. smart-watches, IoT, older mobile devices, and others).

2. Over-fetching and under-fetching

Over/under-fetching is inevitable with RESTful APIs. Using the example above, the endpoint domainName.com/posts/:id fetches data for a specific Post. Every Post is made up of attributes, such as id, body, title, publishingDate, authorId, and others. In REST, the same data object always gets returned; the response is predefined.

In situations where only a Post title and body are needed, over-fetching happens — as more data gets sent over the network than data that is actually utilized. When an entire Post is required, along with related data about its Author, under-fetching gets experienced — as less data gets sent over the network than is actually utilized. Under-fetching leads to bandwidth overuse from multiple requests to the API.

Client-side querying with GraphQL

GraphQL introduces a genuinely unique approach that provides a tremendous amount of flexibility to client-apps. With GraphQL, a query gets sent to your API and precisely what you need is returned — nothing more and nothing less — in a single request. Query results are returned in the same shape as your query, ensuring that response structures are always predictable. These factors allow apps to run faster and be more stable because they are in control of the data they get, and not the server.

"Results are returned in the same shape as queries." /* Query */ { myFriends(first: 2) { items { name age } } } /* Response */ { "data": { "items": [ { "name": "Steve", "age": 27 }, { "name": "Kelly", "age": 31 } ] } } Reality Check ✅

Now, at this point, you probably think GraphQL is as easy as slicing warm butter with a samurai sword. That might be the reality for front-end developers — specifically developers consuming GraphQL APIs. However, when it comes to server-side setup, someone has to make the sausage. Our friend Georgia GraphQL put in some hard work to become the fantastic professional she is!

Building a GraphQL API, server-side, is something that takes time, energy, and expertise. That said, it's nothing that someone ready for a challenge is unable to handle! There are many different ways to hop in at all levels of abstraction. For example:

  • Un-assisted: If you really want to get your hands dirty, try building a GraphQL API with the help of packages. For instance, like Rails? Checkout graphql-ruby. Love Node.js? Try express-graphql.
  • Assisted: If fully maintaining your server/self-hosting is a priority, something like Graph.cool can help you get going on a GraphQL project.
  • Instant: Tired of writing CRUD boilerplate and want to get going fast? 8base provides an instant GraphQL API and serverless backend that's fully extensible.
Wrapping up

REST was a significant leap forward for web services in enabling highly available resource-specific APIs. That said, its design didn't account for today's proliferation of connected devices, all with differing data constraints and requirements. This oversight has quickly lead to the spread of GraphQL — open-sourced by Facebook in 2015 — for the tremendous flexibility that it gives front-end developers. Working with GraphQL is a fantastic developer experience, both for individual developers as well as teams.

The post Meeting GraphQL at a Cocktail Mixer appeared first on CSS-Tricks.

Paperform

Css Tricks - Thu, 09/26/2019 - 4:15am

Buy or build is a classic debate in technology. Building things yourself might feel less expensive because there is no line item on your credit card bill, but has cost in the form of time. Buying things, believe it or not, is usually less expensive when it comes to technology that isn't your core focus. Build your core technology, buy everything else.

That's what I think of with a tool like Paperform. A powerful form builder like Paperform costs me a few bucks, but saves me countless hours in building something that might become extremely complex and a massive distraction from my more important goals.

Paperform is a form builder, but disguised within a page builder

Imagine you're building a registration form for a conference. (That's a perfect fit for Paperform, by the way, as Paperform has payment features that can even handle the money part.) The page that explains the conference and the registration form for the conference can be, and maybe should be, the same thing.

The Paperform designer makes it quite intuitive to build out a page of content.

It is equally intuitive to sprinkle questions into the page as you are writing and design it, making it an interactive form.

Block editing

As a little aside, I dig how the editor is block-based. That's a trend I can get behind lately, with some of my favorite apps like Notion really embracing it and huge projects like Gutenberg in WordPress.

This feels lighter than both of those, a little bit more like the Dropbox Paper editor. Building a form is just like editing a document is a principle they have and I think they are right on. It really is just like working in a document with perhaps a bit more configuration possibilities when you get into the details.

You've got a lot of power at the question level

With a form builder, you really want that power. You don't want to get knee-deep into building a form only to find out you can't do the thing you need to with the functionality and flow of the form. Here's a bunch of yes's:

  • Can you make a field be required? Yes.
  • Can you apply conditional logic to hide/show fields? Yes.
  • Can you apply put default and placeholder text? Yes.
  • Can you set minimum and maximums? Yes.
  • Can you control the layout? Yes.
  • Can you control the design? Yes.
  • Can you programmatically prefill fields? Yes.
  • Can you have hidden fields? Yes.
  • Can you have complex fields like address and signatures? Yes.

Features like logic on questions, I happen to know, are particularly tricky to nail the UX on, and Paperform does a great job with it. You control the logic from option built naturally into the form builder where you would expect to find it.

Based on a "yes" answer to a yes/no question, I reveal an extra address field. Even the address field has powerful features, like limiting the countries you use. Theming is very natural

Controlling color and typography are right up front and very obvious. Color pickers for all the major typographic elements, and the entire kitchen sink of Google Fonts for you to pick from.

I really like that at no point does it feel like you are leaving "the place where you're building the form". You can easily flip around between building the content and design and theme and logic and all that while it's saving your work as you go.

All the most common stuff has UI controls for you, and other big features are easy to find, like uploading background images and controlling buttons. Then if you really need to exert 100% control, their highest plan allows you to inject your own CSS into the form.

"After Submission"

What an obvious thing to call it! I love that. This is where you configure everything that happens with the form data after you've captured it. But instead of calling it something dry and obtuse like "Form Data Configuration Options" or something, it's named after what you are thinking: "What happens after the form is submitted? That's what I'm trying to control."

There are three things that I tend to think about after form submission:

  1. Where is the confirmation email going to go?
  2. What does the success message say to the user?
  3. What integrations can I use?

A nice touch? By default, the form is set up to email you all submissions. Do nothing, and you get that. That's probably what you want 90% of the time anyway. But if you want to get in there and manipulate that email with custom destinations, subject lines, and even entirely reformatted content, you've got it.

In the same fashion, you can create custom PDFs from the submitted data, which is a pretty unique feature and I imagine quite important for some folks.

Customizing that success message, which I find to be appropriate pretty much 100% of the time, is just a matter of changing two fields.

Integrations-wise, for me, the big ones I find myself using are:

  1. Make a Trello card from this.
  2. Put the person on a MailChimp list.
  3. Send a Slack notification.

They've got all those, plus webhooks (hit this arbitrary URL with the data after submission) and Zapier, which covers just about every use case under the sun.

Of course, when you're done building your form, you get a URL you can send people to. For me, the vast majority of the time, what I want to do is embed the form right onto another site, and they have all the options you could want for that as well.

New feature: Calculations

Just a few days ago, they added the ability to essentially do math with form data. There are some fairly straightforward use-cases, like calculating the price of a product based on questions on the form. But the feature was built to be rather open-ended in what you can do with it. Imagine using a calculation as part of a Buzzfeed style quiz that tells you what kind of dragon you are, or disabling submission of the form until a calculation can be made that is satisfactory, or the notification from the form goes to a different person based on the calculation.

I can't cover everything

Paperform is too big for one blog post. I barely mentioned payments, which is a massive feature they handle very well. I'd just end by saying it's a very impressive product and if you're picking a form builder, picking one as feature-rich as Paperform isn't likely to be one you'll regret.

Go Try Paperform

The post Paperform appeared first on CSS-Tricks.

A Dark Mode Toggle with React and ThemeProvider

Css Tricks - Wed, 09/25/2019 - 4:10am

I like when websites have a dark mode option. Dark mode makes web pages easier for me to read and helps my eyes feel more relaxed. Many websites, including YouTube and Twitter, have implemented it already, and we’re starting to see it trickle onto many other sites as well.

In this tutorial, we’re going to build a toggle that allows users to switch between light and dark modes, using a <ThemeProvider wrapper from the styled-components library. We’ll create a useDarkMode custom hook, which supports the prefers-color-scheme media query to set the mode according to the user’s OS color scheme settings.

If that sounds hard, I promise it’s not! Let’s dig in and make it happen.

See the Pen
Day/night mode switch toggle with React and ThemeProvider
by Maks Akymenko (@maximakymenko)
on CodePen.

Let’s set things up

We’ll use create-react-app to initiate a new project:

npx create-react-app my-app cd my-app yarn start

Next, open a separate terminal window and install styled-components:

yarn add styled-components

Next thing to do is create two files. The first is global.js, which will contain our base styling, and the second is theme.js, which will include variables for our dark and light themes:

// theme.js export const lightTheme = { body: '#E2E2E2', text: '#363537', toggleBorder: '#FFF', gradient: 'linear-gradient(#39598A, #79D7ED)', } export const darkTheme = { body: '#363537', text: '#FAFAFA', toggleBorder: '#6B8096', gradient: 'linear-gradient(#091236, #1E215D)', }

Feel free to customize variables any way you want, because this code is used just for demonstration purposes.

// global.js // Source: https://github.com/maximakymenko/react-day-night-toggle-app/blob/master/src/global.js#L23-L41 import { createGlobalStyle } from 'styled-components'; export const GlobalStyles = createGlobalStyle` *, *::after, *::before { box-sizing: border-box; } body { align-items: center; background: ${({ theme }) => theme.body}; color: ${({ theme }) => theme.text}; display: flex; flex-direction: column; justify-content: center; height: 100vh; margin: 0; padding: 0; font-family: BlinkMacSystemFont, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; transition: all 0.25s linear; }

Go to the App.js file. We’re going to delete everything in there and add the layout for our app. Here’s what I did:

import React from 'react'; import { ThemeProvider } from 'styled-components'; import { lightTheme, darkTheme } from './theme'; import { GlobalStyles } from './global'; function App() { return ( <ThemeProvider theme={lightTheme}> <> <GlobalStyles /> <button>Toggle theme</button> <h1>It's a light theme!</h1> <footer> </footer> </> </ThemeProvider> ); } export default App;

This imports our light and dark themes. The ThemeProvider component also gets imported and is passed the light theme (lightTheme) styles inside. We also import GlobalStyles to tighten everything up in one place.

Here’s roughly what we have so far:

Now, the toggling functionality

There is no magic switching between themes yet, so let’s implement toggling functionality. We are only going to need a couple lines of code to make it work.

First, import the useState hook from react:

// App.js import React, { useState } from 'react';

Next, use the hook to create a local state which will keep track of the current theme and add a function to switch between themes on click:

// App.js const [theme, setTheme] = useState('light'); // The function that toggles between themes const toggleTheme = () => { // if the theme is not light, then set it to dark if (theme === 'light') { setTheme('dark'); // otherwise, it should be light } else { setTheme('light'); } }

After that, all that’s left is to pass this function to our button element and conditionally change the theme. Take a look:

// App.js import React, { useState } from 'react'; import { ThemeProvider } from 'styled-components'; import { lightTheme, darkTheme } from './theme'; import { GlobalStyles } from './global'; // The function that toggles between themes function App() { const [theme, setTheme] = useState('light'); const toggleTheme = () => { if (theme === 'light') { setTheme('dark'); } else { setTheme('light'); } } // Return the layout based on the current theme return ( <ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}> <> <GlobalStyles /> // Pass the toggle functionality to the button <button onClick={toggleTheme}>Toggle theme</button> <h1>It's a light theme!</h1> <footer> </footer> </> </ThemeProvider> ); } export default App; How does it work? // global.js background: ${({ theme }) => theme.body}; color: ${({ theme }) => theme.text}; transition: all 0.25s linear;

Earlier in our GlobalStyles, we assigned background and color properties to values from the theme object, so now, every time we switch the toggle, values change depending on the darkTheme and lightTheme objects that we are passing to ThemeProvider. The transition property allows us to make this change a little more smoothly than working with keyframe animations.

Now we need the toggle component

We’re generally done here because you now know how to create toggling functionality. However, we can always do better, so let’s improve the app by creating a custom Toggle component and make our switch functionality reusable. That’s one of the key benefits to making this in React, right?

We’ll keep everything inside one file for simplicity’s sake,, so let’s create a new one called Toggle.js and add the following:

// Toggle.js import React from 'react' import { func, string } from 'prop-types'; import styled from 'styled-components'; // Import a couple of SVG files we'll use in the design: https://www.flaticon.com import { ReactComponent as MoonIcon } from 'icons/moon.svg'; import { ReactComponent as SunIcon } from 'icons/sun.svg'; const Toggle = ({ theme, toggleTheme }) => { const isLight = theme === 'light'; return ( <button onClick={toggleTheme} > <SunIcon /> <MoonIcon /> </button> ); }; Toggle.propTypes = { theme: string.isRequired, toggleTheme: func.isRequired, } export default Toggle;

You can download icons from here and here. Also, if we want to use icons as components, remember about importing them as React components.

We passed two props inside: the theme will provide the current theme (light or dark) and toggleTheme function will be used to switch between them. Below we created an isLight variable, which will return a boolean value depending on our current theme. We’ll pass it later to our styled component.

We’ve also imported a styled function from styled-components, so let’s use it. Feel free to add this on top your file after the imports or create a dedicated file for that (e.g. Toggle.styled.js) like I have below. Again, this is purely for presentation purposes, so you can style your component as you see fit.

// Toggle.styled.js const ToggleContainer = styled.button` background: ${({ theme }) => theme.gradient}; border: 2px solid ${({ theme }) => theme.toggleBorder}; border-radius: 30px; cursor: pointer; display: flex; font-size: 0.5rem; justify-content: space-between; margin: 0 auto; overflow: hidden; padding: 0.5rem; position: relative; width: 8rem; height: 4rem; svg { height: auto; width: 2.5rem; transition: all 0.3s linear; // sun icon &:first-child { transform: ${({ lightTheme }) => lightTheme ? 'translateY(0)' : 'translateY(100px)'}; } // moon icon &:nth-child(2) { transform: ${({ lightTheme }) => lightTheme ? 'translateY(-100px)' : 'translateY(0)'}; } } `;

Importing icons as components allows us to directly change the styles of the SVG icons. We’re checking if the lightTheme is an active one, and if so, we move the appropriate icon out of the visible area — sort of like the moon going away when it’s daytime and vice versa.

Don’t forget to replace the button with the ToggleContainer component in Toggle.js, regardless of whether you’re styling in separate file or directly in Toggle.js. Be sure to pass the isLight variable to it to specify the current theme. I called the prop lightTheme so it would clearly reflect its purpose.

The last thing to do is import our component inside App.js and pass required props to it. Also, to add a bit more interactivity, I’ve passed condition to toggle between "light" and “dark" in the heading when the theme changes:

// App.js <Toggle theme={theme} toggleTheme={toggleTheme} /> <h1>It's a {theme === 'light' ? 'light theme' : 'dark theme'}!</h1>

Don’t forget to credit the flaticon.com authors for the providing the icons.

// App.js <span>Credits:</span> <small><b>Sun</b> icon made by <a href="https://www.flaticon.com/authors/smalllikeart">smalllikeart</a> from <a href="https://www.flaticon.com">www.flaticon.com</a></small> <small><b>Moon</b> icon made by <a href="https://www.freepik.com/home">Freepik</a> from <a href="https://www.flaticon.com">www.flaticon.com</a></small>

Now that’s better:

The useDarkMode hook

While building an application, we should keep in mind that the app must be scalable, meaning, reusable, so we can use in it many places, or even different projects.

That is why it would be great if we move our toggle functionality to a separate place — so, why not to create a dedicated account hook for that?

Let’s create a new file called useDarkMode.js in the project src directory and move our logic into this file with some tweaks:

// useDarkMode.js import { useEffect, useState } from 'react'; export const useDarkMode = () => { const [theme, setTheme] = useState('light'); const toggleTheme = () => { if (theme === 'light') { window.localStorage.setItem('theme', 'dark') setTheme('dark') } else { window.localStorage.setItem('theme', 'light') setTheme('light') } }; useEffect(() => { const localTheme = window.localStorage.getItem('theme'); localTheme && setTheme(localTheme); }, []); return [theme, toggleTheme] };

We’ve added a couple of things here. We want our theme to persist between sessions in the browser, so if someone has chosen a dark theme, that’s what they’ll get on the next visit to the app. That’s a huge UX improvement. For this reasons we use localStorage.

We’ve also implemented the useEffect hook to check on component mounting. If the user has previously selected a theme, we will pass it to our setTheme function. In the end, we will return our theme, which contains the chosen theme and toggleTheme function to switch between modes.

Now, let’s implement the useDarkMode hook. Go into App.js, import the newly created hook, destructure our theme and toggleTheme properties from the hook, and, put them where they belong:

// App.js import React from 'react'; import { ThemeProvider } from 'styled-components'; import { useDarkMode } from './useDarkMode'; import { lightTheme, darkTheme } from './theme'; import { GlobalStyles } from './global'; import Toggle from './components/Toggle'; function App() { const [theme, toggleTheme] = useDarkMode(); const themeMode = theme === 'light' ? lightTheme : darkTheme; return ( <ThemeProvider theme={themeMode}> <> <GlobalStyles /> <Toggle theme={theme} toggleTheme={toggleTheme} /> <h1>It's a {theme === 'light' ? 'light theme' : 'dark theme'}!</h1> <footer> Credits: <small>Sun icon made by smalllikeart from www.flaticon.com</small> <small>Moon icon made by Freepik from www.flaticon.com</small> </footer> </> </ThemeProvider> ); } export default App;

This almost works almost perfectly, but there is one small thing we can do to make our experience better. Switch to dark theme and reload the page. Do you see that the sun icon loads before the moon icon for a brief moment?

That happens because our useState hook initiates the light theme initially. After that, useEffect runs, checks localStorage and only then sets the theme to dark.

So far, I found two solutions. The first is to check if there is a value in localStorage in our useState:

// useDarkMode.js const [theme, setTheme] = useState(window.localStorage.getItem('theme') || 'light');

However, I am not sure if it’s a good practice to do checks like that inside useState, so let me show you a second solution, that I’m using.

This one will be a bit more complicated. We will create another state and call it componentMounted. Then, inside the useEffect hook, where we check our localTheme, we’ll add an else statement, and if there is no theme in localStorage, we’ll add it. After that, we’ll set setComponentMounted to true. In the end, we add componentMounted to our return statement.

// useDarkMode.js import { useEffect, useState } from 'react'; export const useDarkMode = () => { const [theme, setTheme] = useState('light'); const [componentMounted, setComponentMounted] = useState(false); const toggleTheme = () => { if (theme === 'light') { window.localStorage.setItem('theme', 'dark'); setTheme('dark'); } else { window.localStorage.setItem('theme', 'light'); setTheme('light'); } }; useEffect(() => { const localTheme = window.localStorage.getItem('theme'); if (localTheme) { setTheme(localTheme); } else { setTheme('light') window.localStorage.setItem('theme', 'light') } setComponentMounted(true); }, []); return [theme, toggleTheme, componentMounted] };

You might have noticed that we’ve got some pieces of code that are repeated. We always try to follow the DRY principle while writing the code, and right here we’ve got a chance to use it. We can create a separate function that will set our state and pass theme to the localStorage. I believe, that the best name for it will be setTheme, but we’ve already used it, so let’s call it setMode:

// useDarkMode.js const setMode = mode => { window.localStorage.setItem('theme', mode) setTheme(mode) };

With this function in place, we can refactor our useDarkMode.js a little:

// useDarkMode.js import { useEffect, useState } from 'react'; export const useDarkMode = () => { const [theme, setTheme] = useState('light'); const [componentMounted, setComponentMounted] = useState(false); const setMode = mode => { window.localStorage.setItem('theme', mode) setTheme(mode) }; const toggleTheme = () => { if (theme === 'light') { setMode('dark'); } else { setMode('light'); } }; useEffect(() => { const localTheme = window.localStorage.getItem('theme'); if (localTheme) { setTheme(localTheme); } else { setMode('light'); } setComponentMounted(true); }, []); return [theme, toggleTheme, componentMounted] };

We’ve only changed code a little, but it looks so much better and is easier to read and understand!

Did the component mount?

Getting back to componentMounted property. We will use it to check if our component has mounted because this is what happens in useEffect hook.

If it hasn’t happened yet, we will render an empty div:

// App.js if (!componentMounted) { return <div /> };

Here is how complete code for the App.js:

// App.js import React from 'react'; import { ThemeProvider } from 'styled-components'; import { useDarkMode } from './useDarkMode'; import { lightTheme, darkTheme } from './theme'; import { GlobalStyles } from './global'; import Toggle from './components/Toggle'; function App() { const [theme, toggleTheme, componentMounted] = useDarkMode(); const themeMode = theme === 'light' ? lightTheme : darkTheme; if (!componentMounted) { return <div /> }; return ( <ThemeProvider theme={themeMode}> <> <GlobalStyles /> <Toggle theme={theme} toggleTheme={toggleTheme} /> <h1>It's a {theme === 'light' ? 'light theme' : 'dark theme'}!</h1> <footer> <span>Credits:</span> <small><b>Sun</b> icon made by <a href="https://www.flaticon.com/authors/smalllikeart">smalllikeart</a> from <a href="https://www.flaticon.com">www.flaticon.com</a></small> <small><b>Moon</b> icon made by <a href="https://www.freepik.com/home">Freepik</a> from <a href="https://www.flaticon.com">www.flaticon.com</a></small> </footer> </> </ThemeProvider> ); } export default App; Using the user’s preferred color scheme

This part is not required, but it will let you achieve even better user experience. This media feature is used to detect if the user has requested the page to use a light or dark color theme based on the settings in their OS. For example, if a user’s default color scheme on a phone or laptop is set to dark, your website will change its color scheme accordingly to it. It’s worth noting that this media query is still a work in progress and is included in the Media Queries Level 5 specification, which is in Editor’s Draft.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

DesktopChromeOperaFirefoxIEEdgeSafari766267No7612.1Mobile / TabletiOS SafariOpera MobileOpera MiniAndroidAndroid ChromeAndroid Firefox13NoNo76No68

The implementation is pretty straightforward. Because we’re working with a media query, we need to check if the browser supports it in the useEffect hook and set appropriate theme. To do that, we’ll use window.matchMedia to check if it exists and whether dark mode is supported. We also need to remember about the localTheme because, if it’s available, we don’t want to overwrite it with the dark value unless, of course, the value is set to light.

If all checks are passed, we will set the dark theme.

// useDarkMode.js useEffect(() => { if ( window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches && !localTheme ) { setTheme('dark') } })

As mentioned before, we need to remember about the existence of localTheme — that’s why we need to implement our previous logic where we’ve checked for it.

Here’s what we had from before:

// useDarkMode.js useEffect(() => { const localTheme = window.localStorage.getItem('theme'); if (localTheme) { setTheme(localTheme); } else { setMode('light'); } })

Let’s mix it up. I’ve replaced the if and else statements with ternary operators to make things a little more readable as well:

// useDarkMode.js useEffect(() => { const localTheme = window.localStorage.getItem('theme'); window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches && !localTheme ? setMode('dark') : localTheme ? setTheme(localTheme) : setMode('light');}) })

Here’s the userDarkMode.js file with the complete code:

// useDarkMode.js import { useEffect, useState } from 'react'; export const useDarkMode = () => { const [theme, setTheme] = useState('light'); const [componentMounted, setComponentMounted] = useState(false); const setMode = mode => { window.localStorage.setItem('theme', mode) setTheme(mode) }; const toggleTheme = () => { if (theme === 'light') { setMode('dark') } else { setMode('light') } }; useEffect(() => { const localTheme = window.localStorage.getItem('theme'); window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches && !localTheme ? setMode('dark') : localTheme ? setTheme(localTheme) : setMode('light'); setComponentMounted(true); }, []); return [theme, toggleTheme, componentMounted] };

Give it a try! It changes the mode, persists the theme in localStorage, and also sets the default theme accordingly to the OS color scheme if it’s available.

Congratulations, my friend! Great job! If you have any questions about implementation, feel free to send me a message!

The post A Dark Mode Toggle with React and ThemeProvider appeared first on CSS-Tricks.

Thinking in React Hooks

Css Tricks - Wed, 09/25/2019 - 4:09am

Amelia Wattenberger has written this wonderful and interactive piece about React Hooks and details how they can clean up code and remove all those troubling lifecycle events:

React introduced hooks one year ago, and they've been a game-changer for a lot of developers. There are tons of how-to introduction resources out there, but I want to talk about the fundamental mindset change when switching from React class components to function components + hooks.

Make sure you check out that lovely animation when you select the code, too. It’s a pretty smart effect to show the old way of doing things versus the new and fancy way. Also make sure to check out our very own Intro to React Hooks once you’re finished to find more examples of this pattern in use.

Direct Link to ArticlePermalink

The post Thinking in React Hooks appeared first on CSS-Tricks.

Filtering Data Client-Side: Comparing CSS, jQuery, and React

Css Tricks - Tue, 09/24/2019 - 9:43am

Say you have a list of 100 names:

<ul> <li>Randy Hilpert</li> <li>Peggie Jacobi</li> <li>Ethelyn Nolan Sr.</li> <!-- and then some --> </ul>

...or file names, or phone numbers, or whatever. And you want to filter them client-side, meaning you aren't making a server-side request to search through data and return results. You just want to type "rand" and have it filter the list to include "Randy Hilpert" and "Danika Randall" because they both have that string of characters in them. Everything else isn't included in the results.

Let's look at how we might do that with different technologies.

CSS can sorta do it, with a little help.

CSS can't select things based on the content they contain, but it can select on attributes and the values of those attributes. So let's move the names into attributes as well.

<ul> <li data-name="Randy Hilpert">Randy Hilpert</li> <li data-name="Peggie Jacobi">Peggie Jacobi</li> <li data-name="Ethelyn Nolan Sr.">Ethelyn Nolan Sr.</li> ... </ul>

Now to filter that list for names that contain "rand", it's very easy:

li { display: none; } li[data-name*="rand" i] { display: list-item; }

Note the i on Line 4. That means "case insensitive" which is very useful here.

To make this work dynamically with a filter <input>, we'll need to get JavaScript involved to not only react to the filter being typed in, but generate CSS that matches what is being searched.

Say we have a <style> block sitting on the page:

<style id="cssFilter"> /* dynamically generated CSS will be put in here */ </style>

We can watch for changes on our filter input and generate that CSS:

filterElement.addEventListener("input", e => { let filter = e.target.value; let css = filter ? ` li { display: none; } li[data-name*="${filter}" i] { display: list-item; } ` : ``; window.cssFilter.innerHTML = css; });

Note that we're emptying out the style block when the filter is empty, so all results show.

See the Pen
Filtering Technique: CSS
by Chris Coyier (@chriscoyier)
on CodePen.

I'll admit it's a smidge weird to leverage CSS for this, but Tim Carry once took it way further if you're interested in the concept.

jQuery makes it even easier.

Since we need JavaScript anyway, perhaps jQuery is an acceptable tool. There are two notable changes here:

  • jQuery can select items based on the content they contain. It has a selector API just for this. We don't need the extra attribute anymore.
  • This keeps all the filtering to a single technology.

We still watch the input for typing, then if we have a filter term, we hide all the list items and reveal the ones that contain our filter term. Otherwise, we reveal them all again:

const listItems = $("li"); $("#filter").on("input", function() { let filter = $(this).val(); if (filter) { listItems.hide(); $(`li:contains('${filter}')`).show(); } else { listItems.show(); } });

It's takes more fiddling to make the filter case-insensitive than CSS does, but we can do it by overriding the default method:

jQuery.expr[':'].contains = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; };

See the Pen
Filtering Technique: jQuery
by Chris Coyier (@chriscoyier)
on CodePen.

React can do it with state and rendering only what it needs.

There is no one-true-way to do this in React, but I would think it's React-y to keep the list of names as data (like an Array), map over them, and only render what you need. Changes in the input filter the data itself and React re-renders as necessary.

If we have an names = [array, of, names], we can filter it pretty easily:

filteredNames = names.filter(name => { return name.includes(filter); });

This time, case sensitivity can be done like this:

filteredNames = names.filter(name => { return name.toUpperCase().includes(filter.toUpperCase()); });

Then we'd do the typical .map() thing in JSX to loop over our array and output the names.

See the Pen
Filtering Technique: React
by Chris Coyier (@chriscoyier)
on CodePen.

I don't have any particular preference

This isn't the kind of thing you choose a technology for. You do it in whatever technology you already have. I also don't think any one approach is particularly heavier than the rest in terms of technical debt.

The post Filtering Data Client-Side: Comparing CSS, jQuery, and React appeared first on CSS-Tricks.

Filtering Data Client-Side: Comparing CSS, jQuery, and React

Css Tricks - Tue, 09/24/2019 - 9:43am

Say you have a list of 100 names:

<ul> <li>Randy Hilpert</li> <li>Peggie Jacobi</li> <li>Ethelyn Nolan Sr.</li> <!-- and then some --> </ul>

...or file names, or phone numbers, or whatever. And you want to filter them client-side, meaning you aren't making a server-side request to search through data and return results. You just want to type "rand" and have it filter the list to include "Randy Hilpert" and "Danika Randall" because they both have that string of characters in them. Everything else isn't included in the results.

Let's look at how we might do that with different technologies.

CSS can sorta do it, with a little help.

CSS can't select things based on the content they contain, but it can select on attributes and the values of those attributes. So let's move the names into attributes as well.

<ul> <li data-name="Randy Hilpert">Randy Hilpert</li> <li data-name="Peggie Jacobi">Peggie Jacobi</li> <li data-name="Ethelyn Nolan Sr.">Ethelyn Nolan Sr.</li> ... </ul>

Now to filter that list for names that contain "rand", it's very easy:

li { display: none; } li[data-name*="rand" i] { display: list-item; }

Note the i on Line 4. That means "case insensitive" which is very useful here.

To make this work dynamically with a filter <input>, we'll need to get JavaScript involved to not only react to the filter being typed in, but generate CSS that matches what is being searched.

Say we have a <style> block sitting on the page:

<style id="cssFilter"> /* dynamically generated CSS will be put in here */ </style>

We can watch for changes on our filter input and generate that CSS:

filterElement.addEventListener("input", e => { let filter = e.target.value; let css = filter ? ` li { display: none; } li[data-name*="${filter}" i] { display: list-item; } ` : ``; window.cssFilter.innerHTML = css; });

Note that we're emptying out the style block when the filter is empty, so all results show.

See the Pen
Filtering Technique: CSS
by Chris Coyier (@chriscoyier)
on CodePen.

I'll admit it's a smidge weird to leverage CSS for this, but Tim Carry once took it way further if you're interested in the concept.

jQuery makes it even easier.

Since we need JavaScript anyway, perhaps jQuery is an acceptable tool. There are two notable changes here:

  • jQuery can select items based on the content they contain. It has a selector API just for this. We don't need the extra attribute anymore.
  • This keeps all the filtering to a single technology.

We still watch the input for typing, then if we have a filter term, we hide all the list items and reveal the ones that contain our filter term. Otherwise, we reveal them all again:

const listItems = $("li"); $("#filter").on("input", function() { let filter = $(this).val(); if (filter) { listItems.hide(); $(`li:contains('${filter}')`).show(); } else { listItems.show(); } });

It's takes more fiddling to make the filter case-insensitive than CSS does, but we can do it by overriding the default method:

jQuery.expr[':'].contains = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; };

See the Pen
Filtering Technique: jQuery
by Chris Coyier (@chriscoyier)
on CodePen.

React can do it with state and rendering only what it needs.

There is no one-true-way to do this in React, but I would think it's React-y to keep the list of names as data (like an Array), map over them, and only render what you need. Changes in the input filter the data itself and React re-renders as necessary.

If we have an names = [array, of, names], we can filter it pretty easily:

filteredNames = names.filter(name => { return name.includes(filter); });

This time, case sensitivity can be done like this:

filteredNames = names.filter(name => { return name.toUpperCase().includes(filter.toUpperCase()); });

Then we'd do the typical .map() thing in JSX to loop over our array and output the names.

See the Pen
Filtering Technique: React
by Chris Coyier (@chriscoyier)
on CodePen.

I don't have any particular preference

This isn't the kind of thing you choose a technology for. You do it in whatever technology you already have. I also don't think any one approach is particularly heavier than the rest in terms of technical debt.

The post Filtering Data Client-Side: Comparing CSS, jQuery, and React appeared first on CSS-Tricks.

Syndicate content
©2003 - Present Akamai Design & Development.