FluentOrText.jsx (1312B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 import React from "react"; 6 7 /** 8 * Set text on a child element/component depending on if the message is already 9 * translated plain text or a fluent id with optional args. 10 */ 11 export class FluentOrText extends React.PureComponent { 12 render() { 13 // Ensure we have a single child to attach attributes 14 const { children, message } = this.props; 15 const child = children ? React.Children.only(children) : <span />; 16 17 // For a string message, just use it as the child's text 18 let grandChildren = message; 19 let extraProps; 20 21 // Convert a message object to set desired fluent-dom attributes 22 if (typeof message === "object") { 23 const args = message.args || message.values; 24 extraProps = { 25 "data-l10n-args": args && JSON.stringify(args), 26 "data-l10n-id": message.id || message.string_id, 27 }; 28 29 // Use original children potentially with data-l10n-name attributes 30 grandChildren = child.props.children; 31 } 32 33 // Add the message to the child via fluent attributes or text node 34 return React.cloneElement(child, extraProps, grandChildren); 35 } 36 }