react icon indicating copy to clipboard operation
react copied to clipboard

How to replace parts of a string with a component?

Open binarykitchen opened this issue 11 years ago • 40 comments

I have this code which is obviously not working:

    _.each(matches, (match) ->
      string = string.replace(match, ->
        <span className="match" key={i++}>{match}</span>
      )
    )

Because that would result into a string mixed with objects. Bad I know. But how can I add React components inside a string? All I want is to highlight parts of a string with a react component. A tough case to crack I guess.

binarykitchen avatar Mar 12 '15 02:03 binarykitchen

something like this should work :

const escapeRE = new RegExp(/([.*+?^=!:$(){}|[\]\/\\])/g)
const safeRE = (string) => {
  return string.replace(escapeRE, "\\$1")
}

class Hightlight extends Component {
  static propTypes = {
    match : PropTypes.string,
    string : PropTypes.string,
  }

  render() {
    return (
      <span
        dangerouslySetInnerHTML={{
          __html : string.replace(safeRE(this.props.match), "<strong className\"match\">$1</strong>")
        }} />
    )
  }
}

bloodyowl avatar Mar 12 '15 02:03 bloodyowl

Yes, I've been thinking of abusing dangerouslySetInnerHTML but I do not like this idea. This method labelled as dangerously for good reasons.

Is there no way to teach React to parse jsx within a string? Have React parse i.E.

var example = "this one word <span className="match" key={i++}>hello</span> is highlighted"

and return this in a render method?

binarykitchen avatar Mar 12 '15 02:03 binarykitchen

@binarykitchen You can construct React elements dynamically and that's what you need to do here, you just can't do it with only string replacement.

syranide avatar Mar 12 '15 08:03 syranide

@syranide Yes, I already know that. My point is: wouldn't this be a nice JSX/React feature? Parse a string and turn any tags inside into child React components.

binarykitchen avatar Mar 12 '15 20:03 binarykitchen

You can use the split function with a regex and then replace the captured parts, like so:

var parts = "I am a cow; cows say moo. MOOOOO.".split(/(\bmoo+\b)/gi);
for (var i = 1; i < parts.length; i += 2) {
  parts[i] = <span className="match" key={i}>{parts[i]}</span>;
}
return <div>{parts}</div>;

Let me know if that's unclear.

sophiebits avatar Mar 12 '15 20:03 sophiebits

Parsing JSX at runtime is error-prone and slow, and can easily have security implications – it wouldn't inherently be any safer than dangerouslySetInnerHTML is.

sophiebits avatar Mar 12 '15 20:03 sophiebits

that can be a bit of an issue with type case

— mlb

On 12 mars 2015, at 21:37, Ben Alpert [email protected] wrote:

You can use the split function with a regex and then replace the captured parts, like so:

var parts = "I am a cow; cows say moo. MOOOOO.".split(/(\bmoo+\b)/gi); for (var i = 1; i < parts.length; i += 2) { parts[i] = {parts[i]}; } return

{parts}
; Let me know if that's unclear.

— Reply to this email directly or view it on GitHub.

bloodyowl avatar Mar 12 '15 20:03 bloodyowl

I ran into this issue as well when trying to highlight parts of a string programatically (i.e. replace with <span> tags). I ended up creating a module based on @spicyj's solution above. For anyone interested: iansinnott/react-string-replace

iansinnott avatar Feb 13 '16 00:02 iansinnott

@iansinnott Thanks for sharing that. I started using it then realized I'm going to need the full String.prototype.replace API (needed access to the individual matching groups for a regexp within the replace function). I realized the change will be more than a simple patch (and require an API change) so I created a new repo: https://github.com/oztune/string-replace-to-array

oztune avatar Apr 28 '16 19:04 oztune

If react-string-replace doesn't fit your requirements:

https://github.com/EfogDev/react-process-string

efogdev avatar Mar 10 '17 02:03 efogdev

The following worked for me as way to highlight keyword(s) within a string of text, without dangerously setting HTML:

/**
 * Find and highlight relevant keywords within a block of text
 * @param  {string} label - The text to parse
 * @param  {string} value - The search keyword to highlight
 * @return {object} A JSX object containing an array of alternating strings and JSX
 */
const formatLabel = (label, value) => {
  if (!value) {
    return label;
  }
  return (<span>
    { label.split(value)
      .reduce((prev, current, i) => {
        if (!i) {
          return [current];
        }
        return prev.concat(<b key={value + current}>{ value }</b>, current);
      }, [])
    }
  </span>);
};

formatLabel('Lorem ipsum dolor sit amet', 'dolor');
// <span>Lorem ipsum <b>dolor</b> sit amet</span>

richardwestenra avatar Apr 03 '17 14:04 richardwestenra

I needed something like this for mentions matching some pattern so it can wrap multiple values and did some changes to the @richardwestenra solution. Maybe it will be useful for someone.

/**
 * Find and highlight mention given a matching pattern within a block of text
 * @param {string} text - The text to parse
 * @param {array} values - Values to highlight
 * @param {RegExp} regex - The search pattern to highlight 
 * @return {object} A JSX object containing an array of alternating strings and JSX
 */
const formatMentionText = (text, values, regex) => { 
    if (!values.length)
        return text;

    return (<div>
        {text.split(regex)
            .reduce((prev, current, i) => {
                if (!i)
                    return [current];

                return prev.concat(
                    values.includes(current)  ?
                        <mark key={i + current}>
                            {current}
                        </mark>
                        : current
                );
            }, [])}
    </div>);
};

const text = 'Lorem ipsum dolor sit amet [[Jonh Doe]] and [[Jane Doe]]';
const values = ['Jonh Doe', 'Jane Doe'];
const reg = new RegExp(/\[\[(.*?)\]\]/); // Match text inside two square brackets

formatMentionText(text, values, reg);
// Lorem ipsum dolor sit amet <mark>Jonh Doe</mark> and <mark>Jane Doe</mark>

EliecerC avatar Dec 14 '17 16:12 EliecerC

I had a similar issue and I solved it with react portals, to easily find the node, I replaced the string with a div and rendered my react component using createPortal into that div.

rmtngh avatar Jun 21 '18 16:06 rmtngh

@rmtngh I'm curious why you'd need to do that. It seems like it might be overkill. Are you interlacing non-react code?

Regarding solutions to this problem, I'd like to re-recommend string-replace-to-array (I'm the author). It's been battle and time-tested on multiple environments. It's also quite small (the entire library is this file https://github.com/oztune/string-replace-to-array/blob/master/string-replace-to-array.js).

Here's a usage example with regex:

import replace from 'string-replace-to-array'

// The API is designed to match the native 'String.replace',
// except it can handle non-string replacements.
replace(
  'Hello Hermione Granger...',
  /(Hermione) (Granger)/g,
  function (fullName, firstName, lastName, offset, string) {
    return <Person firstName={ firstName } lastName={ lastName } key={ offset } />
  }
)

// output: ['Hello ', <Person firstName="Hermione" lastName="Granger" key={ 0 } />, ...]

oztune avatar Jun 21 '18 22:06 oztune

@oztune Thanks for your reply, In this case I have a string of html markup coming from a wysiwyg editor of a CMS and I'd like to place react components in certain places inside that markup. Do you think it would be better to use a library instead of using portals? I think what portal does is to just render the component inside another node instead of nearest node which wouldn't be more expensive than rendering a normal component and the only extra step is to replace the string which can be done with native js replace. Am I missing anything? Will there be any advantages in using the library instead?

rmtngh avatar Jun 22 '18 06:06 rmtngh

@rmtngh I'd say it depends on what you're trying to do. If you're just trying to sprinkle some React components in different areas of your DOM tree, and the tree isn't already being rendered with React, portals are the way to go. The method I mentioned is most useful when the parts you're trying to replace are already rendered inside of a React component.

oztune avatar Jun 22 '18 15:06 oztune

Here's the code that returns an array of nodes given text and pattern:


const highlightPattern = (text, pattern) => {
  const splitText = text.split(pattern);

  if (splitText.length <= 1) {
    return text;
  }

  const matches = text.match(pattern);

  return splitText.reduce((arr, element, index) => (matches[index] ? [
    ...arr,
    element,
    <mark>
      {matches[index]}
    </mark>,
  ] : [...arr, element]), []);
};

wojtekmaj avatar Jul 12 '18 10:07 wojtekmaj

Thank you @wojtekmaj My version for groups in pattern:

const replacePatternToComponent = (text, pattern, Component) => {
  const splitText = text.split(pattern);
  const matches = text.match(pattern);

  if (splitText.length <= 1) {
    return text;
  }

  return splitText.reduce((arr, element) => {
      if (!element) return arr;

      if(matches.includes(element)) {
        return [...arr, Component];
      }

      return [...arr, element];
    },
    []
  );
};

const string = 'Foo [first] Bar [second]';
const pattern = /(\[first\])|(\[second\])/g;

replacePatternToComponent(string, pattern, <Component />);

alex9pro1 avatar Sep 05 '18 11:09 alex9pro1

Approach using typescript:

const formatString = (
  str: string,
  formatingFunction?: (value: number | string) => React.ReactNode,
  ...values: Array<number | string>
) => {
  const templateSplit = new RegExp(/{(\d)}/g);
  const isNumber = new RegExp(/^\d+$/);
  const splitedText = str.split(templateSplit);
  return splitedText.map(sentence => {
    if (isNumber.test(sentence)) {
      const value = values[Number(sentence)];
      return Boolean(formatingFunction) ? formatingFunction(value) : value;
    }
    return sentence;
  });
};

Example of use:

const str = '{0} test {1} test';
formatString(str, value => <b>{value}</b>, value1, value2);

Result: <b>value1</b> test <b>value2</b> test

pedrodurek avatar Jan 10 '19 20:01 pedrodurek

@rmtngh could you provide a sample of how you achieved the markup enrichment through createportal? I'm looking to do the same.

Dashue avatar Jan 28 '19 17:01 Dashue