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
linksfunction. - Forgetting to import the CSS file or using a wrong path in
href. - Using
linksin 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
| Property | Description | Example |
|---|---|---|
| rel | Type of linked resource | 'stylesheet', 'preload', 'icon' |
| href | URL or path to resource | '/styles/global.css' |
| as | Resource type for preload links | 'style', 'script' |
| type | MIME type of linked resource | 'text/css' |
| crossOrigin | CORS 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.