how to make a message without wrapping in span in react-intl

5.1k Views Asked by At

i have a problem with yahoo/react-intl thats i want to make messages in string type but when im using FormattedMessage it gives me message wrapped in span and thats not cool. i tried formatMessage and that not working too. i be very thankful for any help or advise this is my code:

import React from 'react';
import {FormattedMessage} from 'react-intl';
export default {
    items: [
        {
            name: <FormattedMessage id='app.dashboard'/>,
            url: '/dashboard',
            icon: 'icon-speedometer',
            badge: {
                variant: 'info',
                text: 'New',
            },
        },
        {
            title: true,
            name:  <FormattedMessage id='app.dashboard'/>,
            // optional wrapper object
            wrapper: {
                // required valid HTML5 element tag
                element: 'strong',
                // optional valid JS object with JS API naming ex: { className: "my-class", style: { fontFamily: "Verdana" }, id: "my-id"}
                attributes: {},
            },
            // optional class names space delimited list for title item ex: "text-center"
            class: '',`enter code here`
        },
3

There are 3 best solutions below

0
On

The solution here is to upgrade react-intl to version 3.

In version 3, the <FormattedMesage> (and similarly others react-intl components) is rendering into React.Fragment.

If you want to render it to something else you can specify textComponent prop on IntlProvider, eg.:

<IntlProvider textComponent="span" />

See info in Migration Guide (v2 -> v3).

0
On

Given that you inject the intl context by yourself, Then you can use the formatMessage function.

For example, in your case:

items: [
  { 
    name: intl.formatMessage({id:'app.dashboard'});
  }
]

To get intl in your component you have two choices:

  1. get it from your component's context
  2. use injectIntl to get it in your props.

If you're not in a component, it gets slightly harder but I would just put the id instead of the formatted message in name and then use the react-intl context when available. Here, in the component that consumes and displays this list of items.

0
On

for use in jsx:

it's rendered as a <span>:

<FormattedMessage id='app.dashboard'/>

it's rendered as an <option>:

<FormattedMessage id='app.dashboard' children={msg=> <option>{msg}</option>}/>

or:

<FormattedMessage id='app.dashboard' tagName="option"/>

it's rendered to nothing:

<FormattedMessage id='app.dashboard' children={msg=> <>{msg}</>}/>

or:

<FormattedMessage  id="app.dashboard">{txt => txt}</FormattedMessage>

To use it in a component, you can use formatMessage() like this:

const App=()=>{
  const value = intl.formatMessage({ id: 'header.nav.login' });
  return(<div>{value}</>)
}