0
0
RemixHow-ToBeginner ยท 3 min read

How to Use links Function in Remix for Styles and Assets

In Remix, the links function is used to add stylesheets or other link tags to your HTML document's <head>. You export a links function from your route module that returns an array of objects describing each link tag, such as stylesheets with rel: 'stylesheet' and href pointing to your CSS file.
๐Ÿ“

Syntax

The links function is exported from a Remix route module and returns an array of objects. Each object represents a <link> tag with properties like rel and href.

  • rel: The relationship of the linked resource, e.g., stylesheet.
  • href: The URL or path to the linked resource.
javascript
export function links() {
  return [
    { rel: 'stylesheet', href: '/styles/global.css' }
  ];
}
๐Ÿ’ป

Example

This example shows how to add a CSS file to a Remix route using the links function. The stylesheet will be included in the HTML <head> automatically.

javascript
import stylesUrl from '~/styles/global.css';

export function links() {
  return [
    { rel: 'stylesheet', href: stylesUrl }
  ];
}

export default function Index() {
  return <h1 className="title">Welcome to Remix!</h1>;
}
Output
<h1 class="title">Welcome to Remix!</h1>
โš ๏ธ

Common Pitfalls

Common mistakes when using the links function include:

  • Not returning an array from the links function.
  • Forgetting to import the CSS file or using a wrong path in href.
  • Using links in components instead of route modules (it only works in route files).

Always ensure the links function is exported from the route module and returns an array of objects.

javascript
/* Wrong: returning an object instead of array */
export function links() {
  return { rel: 'stylesheet', href: '/styles.css' };
}

/* Right: returning an array */
export function links() {
  return [
    { rel: 'stylesheet', href: '/styles.css' }
  ];
}
๐Ÿ“Š

Quick Reference

PropertyDescriptionExample
relType of linked resource'stylesheet', 'preload', 'icon'
hrefURL or path to resource'/styles/global.css'
asResource type for preload links'style', 'script'
typeMIME type of linked resource'text/css'
crossOriginCORS setting for linked resource'anonymous'
โœ…

Key Takeaways

Export a links function from your Remix route that returns an array of link descriptor objects.
Each object should at least have rel and href properties to define the link tag.
Use links only in route modules, not in components.
Import CSS files to get correct paths when using bundlers.
Always return an array from links, even if it has one item.