%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home/emergentqj/actioncivile/pre-auth/def/static/js/common/components/
Upload File :
Create Path :
Current File : /home/emergentqj/actioncivile/pre-auth/def/static/js/common/components/renderField.js

import React, { useState } from "react";
import { parsePhoneNumber } from "react-phone-number-input";
import {
  bool,
  func,
  object,
  oneOfType,
  string,
} from "prop-types";
import appConfig from "config/countryData";
import { withTranslation } from "react-i18next";
import {
  TextField,
  Radio,
  FormControlLabel,
} from "@material-ui/core";
import MuiPhoneNumber from "material-ui-phone-number";
import { withStyles } from "@material-ui/core/styles";

const styles = () => ({
  textField: {
    fontWeight: 500,
  },
  input: {
    fontWeight: 500,
  },
  cssOutlinedInput: {
    "&::placeholder": {
      color: "blue",
    },
    "&$cssFocused $notchedOutline": {
      borderWidth: "1px",
    },
  },
  cssFocused: {},
  notchedOutline: {},
  inputPadding: {},
  flex: {
    display: "flex",
  },
});

function RenderField(props) {
  const {
    autoComplete,
    autoFocus,
    errorClass,
    errorString,
    id,
    input,
    meta: { touched, error, dirty },
    placeholder,
    skipTouched,
    t,
    triggerOnBlur,
    type,
    defaultCountry,
  } = props;
  const { countryData } = appConfig;
  const initialAvailableCountries = Object.keys(countryData).map((value) => value.toLowerCase());
  const [availableCountries, setAvailableCountries] = useState(initialAvailableCountries);

  const hasError = !!(
    ((skipTouched === true && dirty === true) || touched)
    && (errorString || errorClass || error)
  );

  let helperText;
  if (hasError === true) {
    // if error comes from state
    if (errorString) {
      helperText = errorString;
    }

    if (errorClass && errorClass !== true) {
      helperText = `${t(`form-validator.${errorClass}`)}`;
    }
    if (error) {
      if (error === "Required") {
        if (placeholder) {
          helperText = t("form-validator.labelIsRequired").replace("$label", placeholder);
        }
      } else if (error?.type === "Length") {
        if (placeholder) {
          helperText = t("form-validator.length")
            .replace("$length", error.length)
            .replace("$label", placeholder);
        } else {
          helperText = t("form-validator.length")
            .replace("$length", error.length)
            .replace("$label", "This field");
        }
      } else {
        helperText = `${t(`form-validator.${error.toLowerCase()}`)}`;
      }
    }
  }

  const onBlur = (event) => {
    if (triggerOnBlur && triggerOnBlur === true) {
      input.onBlur(event);
    }
  };

  const onTelFieldBlur = (event) => {
    if (triggerOnBlur && triggerOnBlur === true) {
      input.onBlur(event);
    }

    const currentCountryPrefix = parsePhoneNumber(input.value)?.country?.toLowerCase();

    const newAvailableCountries = currentCountryPrefix
    && !availableCountries.includes(currentCountryPrefix) ? [
        ...availableCountries,
        currentCountryPrefix,
      ] : availableCountries;

    setAvailableCountries(newAvailableCountries);
  };

  const onChange = (event) => {
    input.onChange(event);
  };

  const onFocus = (event) => {
    input.onFocus(event);
  };

  switch (type) {
    case "text":
    case "password":
    case "email":
      return (
        <TextField
          {...input}
          autoComplete={autoComplete}
          autoFocus={autoFocus}
          error={hasError}
          fullWidth
          helperText={helperText}
          id={id}
          label={placeholder}
          name={input.name}
          onBlur={onBlur}
          onChange={onChange}
          onFocus={onFocus}
          size="small"
          type={type}
          variant="outlined"
        />
      );
    case "tel":
      return (
        <MuiPhoneNumber
          // Force MuiPhoneNumber to rerender when availableCountries get a new country
          key={availableCountries.length}
          fullWidth
          variant="outlined"
          id={id}
          name={input.name}
          size="small"
          helperText={helperText}
          error={hasError}
          autoFormat={false}
          defaultCountry={defaultCountry?.toLowerCase()}
          onChange={onChange}
          onBlur={onTelFieldBlur}
          onFocus={onFocus}
          onlyCountries={availableCountries}
          value={input.value}
          label={placeholder}
        />
      );
    case "radio":
      return (
        <FormControlLabel
          control={<Radio />}
          label={placeholder}
          id={id}
          name={input.name}
          onBlur={onBlur}
          onFocus={onFocus}
          onChange={onChange}
          InputLabelProps={{
            shrink: true,
          }}
          error={hasError}
          fullWidth
          helperText={helperText}
        />
      );
    default:
      return (
        <div>
          <label htmlFor={id}>{placeholder}</label>
          <input
            {...input}
            type={type}
            onBlur={onBlur}
            onFocus={onFocus}
            onChange={onChange}
            id={id}
          />
        </div>
      );
  }
}

RenderField.propTypes = {
  autoComplete: string,
  autoFocus: bool,
  classes: object.isRequired,
  className: string,
  errorClass: oneOfType([string, bool]),
  errorString: oneOfType([string, bool]),
  id: string,
  input: object,
  meta: object.isRequired,
  placeholder: string,
  skipTouched: bool,
  t: func.isRequired,
  triggerOnBlur: bool,
  type: string,
  defaultCountry: string,
};

RenderField.defaultProps = {
  autoComplete: "off",
  autoFocus: false,
  className: "",
  errorClass: undefined,
  errorString: "",
  id: "",
  input: {},
  placeholder: "",
  skipTouched: false,
  triggerOnBlur: false,
  type: "",
  defaultCountry: null,
};

export default withTranslation()(withStyles(styles)(RenderField));

Zerion Mini Shell 1.0