npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@vojtechportes/react-substitute

v0.2.1

Published

React substitute utility

Downloads

580

Readme

React Substitute

Highly configurable react substitute utility that can perform placeholder replacement by context values or react components.

Description

React substitute replaces placeholders in a string. Default placeholder format is {placeholder} and can be changed in options by changing patter property. Placeholders can also contain modifiers and local context, that can be handeled in transform function. Format of a modifier in placeholder is {placeholder|modifier:context}. Modifier and context separators can be changed in options by changing modifierSeparator property. If placeholder value is not matched with any key in context object, empty string is returned, unless forceReplace is set to true. In that case, all placeholders will be processed and can be replaced using custom logic in transform function.

Installation

yarn install @vojtechportes/react-substitute

or

npm install @vojtechportes/react-substitute

API

Arguments

  1. str (string): String with placeholders to be replaced
  2. options (object): Options object

Options

  • pattern (RegExp): Placeholder pattern - defaults to {}
  • modifierSeparator (string): Modifier separator - defaults to |
  • contextSeparator (string): Local context separator - defaults to :
  • context (unknown): Object containing structured json object containing values used to replace placeholders - defaults to {}
  • forceReplace (boolean): If set to true, placeholders will be processed even if their values are not in context object - defaults to undefined
  • transform (fn): Transform function with arguments value, placeholder, key, modifiers and context that returns string or number - defaults to undefined
  • contextType ('list' | 'normal' | 'object'): Defines how context should be parsed. List will be split by commas, normal will be returned as is - defaults to normal
  • returnReactElement (boolean): When true react element will be returned, otherwise string - defaults to false
  • components (any[]): React components to be used for substitution: defaults to undefined

Examples

With context object

import { substitute } from '@vojtechportes/react-substitute';
import React, { PropsWithChildren } from 'react';

export interface ILinkProps {
  to?: string;
}

export const Link: React.FC<PropsWithChildren<ILinkProps>> = ({
  children,
  to,
}) => <a href={to}>{children}</a>;

export default function App() {
  const text =
    'Lorem ipsum dolor sit amet {user|123, John Doe}, {user|456, Jane Doe}';

  const substitutedText = substitute(text, {
    transform: (value, _placeholder, key, _modifier, context) => {
      if (key === 'user') {
        const [userId, userName] = context;

        return `<0 to="/users/${userId}">${userName}</0>`;
      }

      return value;
    },
    context: {
      user: '',
    },
    contextSeparator: '|',
    modifierSeparator: ':',
    contextType: 'list',
    components: [<Link />],
    returnReactElement: true,
  });

  return <div className="App">{substitutedText}</div>;

  ReactDOM.render(<App />, document.getElementById('root'));
}

Without context object and with forceReplace set to true

import { substitute } from '@vojtechportes/react-substitute';
import React, { PropsWithChildren } from 'react';

export interface ILinkProps {
  to?: string;
}

export const Link: React.FC<PropsWithChildren<ILinkProps>> = ({
  children,
  to,
}) => <a href={to}>{children}</a>;

export const FauxLink: React.FC<PropsWithChildren<unknown>> = ({
  children,
}) => (
  <span style={{ textDecoration: 'underline', color: 'blue' }}>{children}</span>
);

export default function App() {
  const text =
    'Lorem ipsum dolor sit amet {user|123, John Doe}, {user|456, Jane Doe} {token|789} {group|011} {group}';

  const substitutedText = substitute(text, {
    transform: (value, _placeholder, key, _modifier, context) => {
      if (key === 'user') {
        const [userId, userName] = context;

        return `<0 to="/users/${userId}">${userName}</0>`;
      }

      if (key === 'token') {
        const [tokenId] = context;

        return `<1>${key}: ${tokenId}</1>`;
      }

      const [identifier] = context;

      if (identifier) {
        return `<1>${identifier}</1>`;
      }

      return value;
    },
    forceReplace: true,
    contextSeparator: '|',
    modifierSeparator: ':',
    contextType: 'list',
    components: [<Link />, <FauxLink />],
    returnReactElement: true,
  });

  return <div className="App">{substitutedText}</div>;
}

ReactDOM.render(<App />, document.getElementById('root'));
}