Skip to content

Implement a consumer component #18

@rubeniskov

Description

@rubeniskov

It would be easier to develop if react-i18njs provides a built-in consumer with a customizable arguments using a function called createTrans.

the name of component Trans came from the react implementation of react-i18next

Real case scenario

import React from "react";
import { createUseStyles } from "react-jss";
import { createTrans } from "@k14v/react-i18njss";
import styles from "./styles";

const useStyles = createUseStyles(styles);

const Trans = createTrans({
  component: "a",
});

const Header = ({ children, ...restProps }) => {
  const styles = useStyles(restProps);

  return (
    <header className={styles.header}>
      {children}
      <div className={styles.container}>
        <nav className={styles.navigation} role="navigation">
          <ul>
            <li>
              <Trans href="./#why">About</Trans>
            </li>
            <li>
              <Trans href="./#why">Install</Trans>
            </li>
            <li>
              <Trans href="./#why">Docs</Trans>
            </li>
            <li>
              <Trans href="./#why">Team</Trans>
            </li>
            <li>
              <Trans href="./#why">Blog</Trans>
            </li>
            <li>
              <Trans href="./#why">Forum</Trans>
            </li>
          </ul>
        </nav>
      </div>
    </header>
  );
};

export default Header;

Posible implementation

import React from "react";
import PropTypes from "prop-types";
import { useI18n } from "@k14v/react-i18njs";

const parse = (value, i18n) => {
  if (typeof children === "string") {
    return value;
  }

  if (typeof children === "function") {
    return value(i18n);
  }

  return null;
};

const Trans = ({ component: C, children, ...restProps }) => {
  const i18n = useI18n();
  const value = i18n.trls.__(parse(children, i18n));

  if (C) {
    return <C {...restProps}>value</C>;
  }

  return value;
};

Trans.propTypes = {
  children: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired,
};

export const createTrans = (defaults) => (props) => {
  return <Trans {...defaults} {...props}></Trans>;
};

export default Trans;

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions