Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying filters to nested components

I'm trying to apply a custom filter (for adding properly inflected suffixes in Turkish) using the <Trans> component and interpolation. The problem is that a key part of the sentence that needs to be inflected (the name of a user), is rendered by its own component. Is there a way to conditionally apply a filter to a nested component?

  • I can't directly use the inflection filter on the inner component. The inner component is used in multiple places, and each context may need different filters or none at all.
  • The inner component just gets a user id as a prop, and fetches its own contents (the user's name) through react-redux. The outer component (which owns the sentence context), has no idea about the contents of the inner component.
  • The filters are useful for a single language (Turkish). The filter to be used must be part of the translation file, as all other languages will not use those filters. (Also, choosing a filter is the job of the translator)

Practically it would help if I could do something like that (but that doesn't work)

{  // en.json
   newMessage: "You got a new message from <1>user</1>" 
}

{  // tr.json
   newMessage: "Size {{<1>user</1>, ablative_suffix}} yeni bir mesaj geldi" 
}

Which I wish would render something like "Size Mert'ten yeni bir mesaj geldi" given the user name "Mert". Is there another way to accomplish something like this?


<User>

const User = ({ user }) => <strong>{user ? user.name: null}</strong>;

const mapStateToProps = (state, { id }) => ({ user: state.users[id] });

export default connect(mapStateToProps);

<NewMessage>

export const NewMessage = ({userId}) => 
    <Trans i18nKey="newMessage">
        You got a new message from <User id={userId}/>
    </Trans>;

like image 715
edgerunner Avatar asked Mar 30 '26 22:03

edgerunner


1 Answers

Checkout this solution, https://codesandbox.io/s/react-i18next-2w5c2.

I'm extracting the children on the User component (hacky way) and add it as special value _1_children, then, use it translations, which Trans will inject it as children to the component, therefore, there is children || 'data' as the children of User component.

From all of my attempts, looks like there is not "clean" way to do so, I think that it is better to connect to the redux store by your self (you have the id) and pass the user name as variable like I did.

Anyway, i18next Trans component supports only injecting data from translation to Component and not vice versa.

like image 69
felixmosh Avatar answered Apr 03 '26 15:04

felixmosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!