An open API service indexing awesome lists of open source software.

https://github.com/chrisg86/react-wrap-text

A simple utility to wrap matching substrings in React with custom jsx components
https://github.com/chrisg86/react-wrap-text

highlight jsx react react-utils text-highlighter text-replace

Last synced: 3 months ago
JSON representation

A simple utility to wrap matching substrings in React with custom jsx components

Awesome Lists containing this project

README

          

# ✨ react-wrap-text
A tiny utility for highlighting or replacing specific text matches inside strings with custom React components.

Perfect for inline highlighting, smart mentions, tokenized UI, or simple templating in JSX.

## 🚀 Install
```
npm install react-wrap-text
```

## Usage

### Example 1: Highlight
Use `wrapMatchesInText` if you want to highlight specific parts of the text.

```ts
import { wrapMatchesInText } from 'react-wrap-matches';

// Define an optional wrapper component
const Highlight = ({ children }: { children: React.ReactNode }) => (
{children}
);

const text = "Hit or miss, I guess they never miss, huh?";

const result = wrapMatchesInText(text, "miss", (match, i) => (
{match}
));

// Output:
// Hit or miss, I guess they never miss, huh?
return

{result}

;
```

### Example 2: Replace
Use `wrapMatchesInText` if you want to replace matching parts of the text with a JSX component.

```ts
import { wrapMatchesInText } from 'react-wrap-matches';

const text = "You've scored 100 points!";

const result = wrapMatchesInText(text, "100", (_, i) => (
// This also works with inline jsx
💯
));

// Output
// You've scored 💯 points!
return

{result}

;
```

### Example 3: Advanced - Highlight multiple
Use `wrapMultipleMatchesInText` if you need to highlight/replace multiple substrings.

```ts
import { wrapMultipleMatchesInText } from 'react-wrap-matches';

const Highlight = ({ children }: { children: React.ReactNode }) => (
{children}
);

const HighlightOrange = ({ children }: { children: React.ReactNode }) => (
{children}
);

const text = "This is a test. This test works.";

const multiPayload: Parameters[1] = [
{
target: "This",
render: (match, i) => {match},
},
{
target: "works",
render: (match, i) => {match},
}
];

const result = wrapMultipleMatchesInText(text, multiPayload);

// Output
// This is a test. This test works.
return

{result}

;
```