EN VI

Javascript - React shopify checkout extension, add link into text dynamically?

2024-03-12 18:00:12
How to Javascript - React shopify checkout extension, add link into text dynamically

I am working on a shopify extension react component and want to add text dynamically from settings(shopify feature). My main goal is to find the {link_placeholder} string in to the text and change it with real text. my component looks like this

function Extension() {

const {static_content_text} = useSettings();

const link = "https://test.com";
const link_text = "some link text";

const replacedText = static_content_text.replace(
    /\{LINK_PLACEHOLDER\}/g,
    `<Link appearance="base" to="${link}">${link_text}</Link>`
);

return (
  <BlockStack>
      <Text>
          {replacedText}
      </Text>
  </BlockStack>
  );
}

the problem is that link tags are inserted as a plain text and not rendered as an actual link,

how can it be solved? thanks in advance

Solution:

React will escape plain strings that are rendered, however you can render an array of React content. So, instead of adding your link as text, create an array containing the start of the string, then your link component, then the end of the string.

A non-React example of this (as it makes the snippet much simpler):

const static_content_text = 'Example text with a {LINK_PLACEHOLDER} in the middle'

const textArray = static_content_text
  .split(/\{LINK_PLACEHOLDER\}/g)
  .flatMap((text) => ([
    text, 
    // Replace this string with your component
    // <Link appearance="base" to={link}>{link_text}</Link>
    'Add your link component here instead of this string'
   ]))
  .slice(0, -1)
 
// This is just for the example
console.log(textArray)

/* Then in the render method:
return (
  <BlockStack>
      <Text>
          {textArray}
      </Text>
  </BlockStack>
  )
}
*/

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login