Introducing createInterpolateElement

With the release of WordPress 5.5 there will be a new function available on the wp.element package, createInterpolateElement.

This function creates an interpolated element from a passed in string with specific tags matching how the string should be converted to an element or ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. node given a conversion map value.

This function offers the ability to handle a couple use-cases:

  • When you have a template string with placeholders for where you inject known htmlHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. elements or React components.
  • When you have a translationtranslation The process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. string where you want to communicate placeholders for html elements to those translating the string.

One problem with the above use-cases in the past has been preserving the security of html string rendering within react without using RawHTML or dangerouslySetInnerHTML.

Of course the second use-case above is the primary one for which this function was created. As an example, for the given string:

"This is a <span class="special-text">string</span> with a <a href="https://make.wordpress.org">link</a> and a self-closing <CustomComponent />."

You could make the above translatable via doing something like this:

import { __ } from '@wordpress/i18n';
import { createInterpolateElement } from '@wordpress/element';
import { CustomComponent } from '../custom-component.js';

const translatedString = createInterpolateElement(
  __( 'This is a <span>string</span> with a <a>link</a> and a self-closing <custom_component/>.' ),
  {
    span: <span className="special-text" />,
    a: <a href="https://make.wordpress.org"/>,
    custom_component: <CustomComponent />,
  }
);

#5-5, #core-js, #dev-notes