Zinox
Zinox

Reputation: 535

How can I replace bits or string with React component, react-router-dom Link or an anchor tag <a></a>

How can I replace bits of string with links or components

This is a sample of the data

Ownership of Product/DiJUHl5zCE changed from Org/abcd to Org/efghi
Stage changed to completed for Payment of 254.15 gbp on Cycle Cycle/svgAjnox5t
Ownership of Product/DSGDHFHFDH changed from Org/sdef to Org/juhtr
Stage changed to completed for Payment of 4.15 gbp on Cycle Cycle/fdlkgdfkjdfl

I want to replace

Ownership of Product/DiJUHl5zCE changed from Org/dvju to Org/kijuy

Ownership of Product changed from OrgName to OrgName

Ownership of <a href="/product/Product/DiJUHl5zCE">Product</a> changed from <a href="/org/Org/abcd">OrgName</a> to <a href="/org/Org/efghi">OrgName</a>

and

Stage changed to completed for Payment of 254.15 gbp on Cycle Cycle/svgAjnox5t

Stage changed to completed for Payment of 254.15 gbp on Cycle Cycle

Stage changed to completed for Payment of 254.15 gbp on Cycle <a href="/cycle/Cycle/svgAjnox5t">Cycle</a>

I also have a regex

/([\w\d]+)\/([\w\d-]+)/g;

https://regex101.com/r/VrqlI7/1

that returns the groups but if I use replace() or replaceAll() the second argument returns string and in the browser it comes out as [object, object]

basically pass each line through a function and return a div with bits of text replaced with links

I am relatively new to react. any help much appriciated.

If I use `` at the start enter image description here enter image description here

if I use `` withing the href enter image description here enter image description here

How can I get this to display as links, Please advice

Upvotes: 1

Views: 518

Answers (1)

comonadd
comonadd

Reputation: 1988

You can use replaceAll with a callback

s.replaceAll(/([\w\d]+)\/([\w\d-]+)/g, (a) => {
  if (a.startsWith("Product")) { return `<a href="/product/${a}">${a}</a>` }
  else if (a.startsWith("Org")) { return `<a href="/org/${a}">${a}</a>` }
  else { return a }
})

Edit: If you want to render links as react components, you can split the text by pattern using split() and then map() over the resulting array to replace the parts you need, like this:

const lPrefixMap = { 'Product': '/product/', 'Cycle': '/cycle/', 'Org': '/org/' };
const renderedContent = text.split(/([\w\d]+\/[\w\d-]+)/g).map((v, idx) => {
  if (idx & 1) {
    const linkType = v.split('/')[0];
    const prefix = lPrefixMap[linkType];
    return (<Link to={`${prefix}${v}`}>{v}</Link>);
  }
  return <span>v</span>;
});
// You can then render this in your JSX code like this:
return <div>{renderedContent}</div>

Upvotes: 2

Related Questions