synacor / preact-i18n

Simple localization for Preact.
BSD 3-Clause "New" or "Revised" License
205 stars 18 forks source link

Rendering string instead of object #43

Closed donkeyDau closed 4 years ago

donkeyDau commented 4 years ago

Using <Text> in props of Components leads to [object Object]

grafik

This is due to passing the the Text nested in an object:

const COLUMNS = [
  {
    dataField: 'biddingZone',
    text: <Text id="Balances.tableHeadings.biddingZone" />,
    sort: true,
    filter: 'text',
  }
]

I could use the withText HOC but this messing up my component pros and is cumbersome due to a re-assignment of the translation in the decorator.

Would it be possible to somehow expose the translate function to be directly usable? Or any other possibility to access the translation as a string more handy?

pl12133 commented 4 years ago

I don't see anything wrong with exposing translate directly. Since the Text in your example does not use plural or fields, you can translate it directly using a regular property access:

const text = this.context.intl.dictionary.Balances.tableHeadings.biddingZone;

// it is safer to use `lodash.get`:
import get from 'lodash/get';
const text = get(this.context.intl, 'dictionary.Balances.tableHeadings.biddingZone');

If this is a functional component, the useText hook coming up in https://github.com/synacor/preact-i18n/pull/42 will solve your issue here as well.

donkeyDau commented 4 years ago

Using useText solves this issue. Thank you.

elias6 commented 4 years ago

Can this be reopened? I am currently using preact-i18n to render some text into a component, and now we suddenly have to pass it to a 3rd-party API that expects the text as a string. I can probably come up with something, but it would be so simple and easy if the translate function were exposed.