0

On a daily basis I'm using vue.js but right now I'm working on a react project. I've got this translation method:

function __(key, replace = null) {
    let translation, translationNotFound = true;

    try {
        translation = key.split('.').reduce((t, i) => t[i] || null, window._translations[window._locale].php);

        if (translation) {
            translationNotFound = false;
        }
    } catch (e) {
        translation = key;
    }

    if (translationNotFound) {
        translation = window._translations[window._locale]['json'][key]
            ? window._translations[window._locale]['json'][key]
            : key;
    }

    if (replace) {
        replace.forEach((value, key) => {
            translation = translation.replace(':' + key, value);
        });
    }

    return translation;
}

In vue I'm using a mixin for this so it can be used everywhere. How can I make sure I can use this method in my react components?

Already red lots of articles online but can't figure it out.

0

1 Answer 1

2

Just export your function

const myFunction = (key, replace = null) => {
    let translation, translationNotFound = true;

    try {
        translation = key.split('.').reduce((t, i) => t[i] || null, window._translations[window._locale].php);

        if (translation) {
            translationNotFound = false;
        }
    } catch (e) {
        translation = key;
    }

    if (translationNotFound) {
        translation = window._translations[window._locale]['json'][key]
            ? window._translations[window._locale]['json'][key]
            : key;
    }

    if (replace) {
        replace.forEach((value, key) => {
            translation = translation.replace(':' + key, value);
        });
    }

    return translation;
}

export default myFunction;

When you want to import

import myFunction from 'path/to/the/file'
Sign up to request clarification or add additional context in comments.

2 Comments

Yes but then I've got to import it in all my components!
Personnally, I prefer importing everytime. In this article on the reactjs official blog reactjs.org/blog/2016/07/13/mixins-considered-harmful.html, they explain how to do mixins, why you should not use them and what to do instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.