UNPKG

react-linkify-it

Version:

A super tiny <1KB, dependency-free, highly customizable React utility to turn any pattern in your text into clickable links or custom components. Instantly linkify URLs, emails, twitter handles, hashtags, mentions or anything else out of the box or with y

322 lines (233 loc) β€’ 10.1 kB
# react-linkify-it πŸ”— **A super tiny <1KB, dependency-free, highly customizable React utility to turn any pattern in your text into clickable links or custom components. Instantly linkify URLs, emails, twitter handles, hashtags, mentions or anything else out of the box or with your own rules.** [![Npm version](https://badgen.net/npm/v/react-linkify-it)](https://www.npmjs.com/package/react-linkify-it) [![Build](https://github.com/anantoghosh/react-linkify-it/actions/workflows/node.js.yml/badge.svg)](https://github.com/anantoghosh/react-linkify-it/actions/workflows/node.js.yml) [![NPM bundle size](https://img.shields.io/bundlephobia/minzip/react-linkify-it)](https://bundlephobia.com/package/react-linkify-it) ![Tree shaking supported](https://img.shields.io/badge/Tree%20Shaking-Supported-blue) [![Maintainability](https://api.codeclimate.com/v1/badges/fcb46fb37e7c25990c53/maintainability)](https://codeclimate.com/github/anantoghosh/react-linkify-it/maintainability) [![codecov](https://codecov.io/github/anantoghosh/react-linkify-it/graph/badge.svg?token=1W6XJAO4JY)](https://codecov.io/github/anantoghosh/react-linkify-it) [![Known Vulnerabilities](https://snyk.io/test/github/anantoghosh/react-linkify-it/badge.svg)](https://snyk.io/test/github/anantoghosh/react-linkify-it) <a href="https://github.com/sponsors/anantoghosh" target="_blank"><img alt="Support me on Github" src="https://anantoghosh.github.io/assets/support_github.svg" height="40" /></a> <a href="https://www.buymeacoffee.com/ananto" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="40" /></a> --- ## Why You'll Love react-linkify-it ✨ - ⚑ **Super tiny**: Less than 1KB gzipped after tree shaking! - πŸͺΆ **Zero dependencies**: No bloat, No extra dependencies. Just a single file. - πŸ› οΈ **Ultra customizable**: Linkify any pattern, use your own regex, wrap with any component. Adjust to your specific case as required. - πŸ”— **Prebuilt for you**: URLs, emails, twitter handles, hashtags, mentions - ready out of the box. - πŸ’§ **Generic**: Not just links, wrap any pattern with _any_ component. - 🧩 **Composable**: Nest, combine, and mix patterns as you like. - πŸš€ **Blazing fast**: Single-pass processing. - 🦺 **Safe**: Sanitizes URLs to prevent XSS. - 🌍 **i18n & emoji friendly**: Works with URLs that contain international characters and emojis. - 🧹 **Tree-shakable**: Only what you use gets bundled. - πŸ§ͺ **Production ready**: Thoroughly tested and used in real apps. - βš›οΈ **React support**: Works with React v16.2+ Make your text interactive, your way. Fun, fast, and flexible! πŸŽ‰ --- ## Demo [Code Sandbox](https://codesandbox.io/p/sandbox/react-linkify-it-drynzv) --- ## Installation ```sh npm i react-linkify-it ``` --- ## Usage ### Usage - Prebuilt Components These components make it super easy to linkify common patterns. All accept the following props: - `children` (string | ReactNode, required): The content to scan and linkify. - `className` (string, optional): CSS class for the anchor tag(s) created. #### 1. `<LinkItUrl>` **What it does:** Scans its children for URLs (http, https, www) and wraps them in `<a href="...">` tags. **Props:** - `children` (required): Content to linkify. - `className` (optional): CSS class for the anchor tag. ```jsx import { LinkItUrl } from 'react-linkify-it'; const App = () => ( <div className="App"> <LinkItUrl className="my-link"> <p>add some link https://www.google.com here</p> </LinkItUrl> </div> ); ``` #### 2. `<LinkItTwitter>` **What it does:** Finds Twitter handles (e.g. `@username`) and links them to Twitter profiles. **Props:** - `children` (required): Content to linkify. - `className` (optional): CSS class for the anchor tag. ```jsx import { LinkItTwitter } from 'react-linkify-it'; const App = () => ( <div className="App"> <LinkItTwitter className="twitter-link"> hello @anantoghosh twitter </LinkItTwitter> </div> ); ``` #### 3. `<LinkItEmail>` **What it does:** Finds email addresses and wraps them in `mailto:` links. **Props:** - `children` (required): Content to linkify. - `className` (optional): CSS class for the anchor tag. ```jsx import { LinkItEmail } from 'react-linkify-it'; const App = () => ( <div className="App"> <LinkItEmail className="email-link"> hello example@gmail.com email </LinkItEmail> </div> ); ``` #### 4. `<LinkIt>` (Generic Component) **What it does:** Lets you linkify any pattern using your own regex and custom component. Perfect for advanced use cases or custom patterns. **Props:** - `component` (required): Function `(match, key) => ReactNode` to render each match. - `regex` (required): RegExp to match your pattern. - `children` (required): Content to linkify (string or ReactNode). ```jsx // Example: Linkify all '@mentions' and link internally import { LinkIt } from 'react-linkify-it'; // If using Next.js: import Link from 'next/link'; const mentionRegex = /@([\p{L}\p{N}_]+)/u; const App = () => ( <div className="App"> <LinkIt regex={mentionRegex} component={(match, key) => ( <Link href={`/user/${encodeURIComponent(match.slice(1))}`} key={key}> {match} </Link> )} > Welcome '@anantoghosh' and '@ユーアー' to our app! </LinkIt> </div> ); ``` #### 5. `<LinkItHashtag>` **What it does:** Finds hashtags (e.g. `#OpenSource`, `#ζ—₯本θͺž`) and links them to your chosen platform using a URL template. **Props:** - `children` (required): Content to linkify. - `urlTemplate` (required): URL template with `{hashtag}` placeholder (without the `#`). - `className` (optional): CSS class for the anchor tag. ```jsx import { LinkItHashtag } from 'react-linkify-it'; const App = () => ( <div className="App"> {/* Instagram example with Unicode */} <LinkItHashtag urlTemplate="https://instagram.com/explore/tags/{hashtag}"> Love #sunset and #ζ—₯本θͺž hashtags! </LinkItHashtag> {/* Custom website example */} <LinkItHashtag urlTemplate="https://example.com/tags/{hashtag}"> Discussing #AI and #MachineLearning trends </LinkItHashtag> </div> ); ``` #### 6. `<LinkItMention>` **What it does:** Finds mentions (e.g. `@username`, `@ユーアー`) and links them to your chosen platform using a URL template. **Props:** - `children` (required): Content to linkify. - `urlTemplate` (required): URL template with `{mention}` placeholder (without the `@`). - `className` (optional): CSS class for the anchor tag. ```jsx import { LinkItMention } from 'react-linkify-it'; const App = () => ( <div className="App"> {/* Instagram example with Unicode */} <LinkItMention urlTemplate="https://instagram.com/{mention}"> Welcome @newuser and @ユーアー to our platform! </LinkItMention> {/* Custom website example */} <LinkItMention urlTemplate="https://example.com/users/{mention}"> Shoutout to @octocat and @defunkt for joining! </LinkItMention> </div> ); ``` ### Usage - Generic Function The `linkIt` function is a utility for linkifying any string using your own regex and component, outside of React tree rendering. ```jsx import { linkIt, UrlComponent } from 'react-linkify-it'; const regexToMatch = /@([\w_]+)/g; const App = () => { // 'linkIt' returns an array of React nodes or the original string const output = linkIt( text, // string to linkify (match, key) => <UrlComponent match={match} key={key} />, // your component regexToMatch, // your regex ); return <div className="App">{output}</div>; }; ``` ### Using Multiple Matches You can nest prebuilt components to linkify multiple patterns at once: ```jsx import { LinkItEmail, LinkItUrl, LinkItHashtag, LinkItMention, } from 'react-linkify-it'; const App = () => ( <div className="App"> {/* Linkify URLs and emails together */} <LinkItUrl> <LinkItEmail>hello example@gmail.com https://google.com</LinkItEmail> </LinkItUrl> {/* Linkify hashtags and mentions together */} <LinkItHashtag urlTemplate="https://instagram.com/explore/tags/{hashtag}"> <LinkItMention urlTemplate="https://instagram.com/{mention}"> Welcome @newuser to #ζ—₯本θͺž! </LinkItMention> </LinkItHashtag> </div> ); ``` --- ## Customization All prebuilt components accept the following props: - `className` (string, optional): CSS class for the anchor tag. - `children` (string | ReactNode): Content to linkify. The generic `LinkIt` component accepts: - `component`: Function `(match, key) => ReactNode` to render each match. - `regex`: RegExp to match your pattern. - `children`: Content to linkify. The `linkIt` function accepts: - `text`: String to process. - `component`: Function `(match, key) => ReactNode`. - `regex`: RegExp. You can also import and use the regex patterns directly: ```js import { urlRegex, emailRegex, twitterRegex, } from 'react-linkify-it'; ``` --- ## Acknowledgment This project was made possible due to the incredible work done on the following projects: - [sanitize-url](https://github.com/braintree/sanitize-url) - [react-linkify](https://github.com/tasti/react-linkify) --- ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. --- ## Support Hey πŸ‘‹ If my packages have helped you in any way, consider making a small donation to encourage me to keep contributing. Maintaining good software takes time and effort, and for open-source developers, there are very few incentives to do so. Your contribution is greatly appreciated and will motivate me to continue supporting and developing my packages. <a href="https://github.com/sponsors/anantoghosh" target="_blank"><img alt="Support me on Github" src="https://anantoghosh.github.io/assets/support_github.svg" height="40" /></a> <a href="https://www.buymeacoffee.com/ananto" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="40" /></a>