Skip to content

Replace dangerouslySetInnerHTML with createInterpolateElement in React apps #6759

Description

@delawski

Feature Description

In React components we are often using a combination of dangerouslySetInnerHTML (or <RawHTML>) with one of the i18n functions like __() for rendering translated strings containing HTML elements like:

<p
  dangerouslySetInnerHTML={ {
    __html: __( 'This is <b>bold</b>.', 'amp' ),
  } }
/>

This approach has some limitations. One is that only simple HTML elements can be interpolated this way. E.g. it's not possible to interpolate a React component into a translated string:

- __( 'Go to <ExternalLink href="/?url=https%3A%2F%2Fexample.com%2F">example.com</ExternalLink>', 'amp' );
+ __( 'Go to <a href="/?url=https%3A%2F%2Fexample.com%2F" target="_blank" rel="noopener noreferrer">example.com</a>', 'amp' );

The second issue is that using dangerouslySetInnerHTML along with translated strings has some security concerns.

However, since WordPress 5.5 there's a solution available at our disposal: createInterpolateElement.

Here's how the same example would look like with createInterpolateElement:

createInterpolateElement(
  __( 'Go to <a>example.com</a>', 'amp' ),
  {
    a: <ExternalLink href="https://example.com/" />,
  },
);

We should replace all occurrences of dangerouslySetInnerHTML or <RawHTML> with createInterpolateElement.

Acceptance Criteria

No response

Implementation Brief

No response

QA Testing Instructions

No response

Demo

No response

Changelog Entry

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ChangeloggedWhether the issue/PR has been added to release notes.EnhancementNew feature or improvement of an existing oneInfrastructureChanges impacting testing infrastructure or build toolingP2Low priorityjavascriptPull requests that update Javascript code

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      Sponsor
      SponsoredKunjungi sekarang
      Promo