Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Include multiple class inside CSS module

<footer className={ `${styles.footerArea} ${styles.footerLight}` }>

MULTIPLE CONDITIONAL RENDERINGS IN REACT with ENUM

<TableCell align="center">
  {
    {
      'None': <p>We are not sure about this email.</p>,
      'True': <p>Your provided email is valid.</p>,
      'False': <p>This email is Invalid.</p>,
    }[item.status]
  }
</TableCell>

React onclick pass data

function selectTemplate(id) {
  console.log(id);
}
onClick={() => selectTemplate(template.id)}

Shorthand onSubmit / onClick execution

<form
  onSubmit={e => {
    e.preventDefault();
    setQuery(search);
  }}
>
</form>

Simple WebSocket

const socket = new WebSocket('ws://192.168.1.36:8000/ws');

const [mailLogs, setMailLogs] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  let timeout = 250;

  async function connect () {
    
    var ws = new WebSocket('ws://192.168.1.36:8000/ws');
    let connectInterval;

    // websocket onopen event listener
    ws.onopen = () => {
      setIsLoading(true)
      console.log('connected websocket main component');
      ws.send(JSON.stringify({
        'token': localStorage.getItem('__miu_rsl_at_'),
      }));
      clearTimeout(connectInterval); // clear Interval on on open of websocket connection
      setIsLoading(false)

    };

    ws.onmessage = function(res) {
      setMailLogs(JSON.parse(res.data));
    }

    // websocket onclose event listener
    ws.onclose = e => {
      console.log(
        `Socket is closed. Reconnect will be attempted in ${Math.min(
          10000 / 1000,
          (timeout) / 1000
        )} second.`,
        e.reason
      );

      timeout = timeout + 250; //increment retry interval
      connectInterval = setTimeout(checkCon, Math.min(10000, timeout)); //call check function after timeout
    };

    // websocket onerror event listener
    ws.onerror = err => {
      console.error(
        'Socket encountered error: ',
        err.message,
        'Closing socket'
      );

      ws.close();
    };
  }


  async function checkCon () {
    if (!ws || ws.readyState == WebSocket.CLOSED) connect(); //check if websocket instance is closed, if so call `connect` function.
  }

  useEffect(() => {
    connect()
  }, [])

React-router Multiple path same component

<ProtectedRoute
  component={DashboardView}
  exact
  layout={MainLayout}
  path={['/', '/dashboard']}
/>

Get query param

function useQuery() {
  return new URLSearchParams(window.location.search);
}
let query = useQuery().get('id');

Basic Problem Solution

If formik form is not being submitted, it means the validation is catching something which is not available.

Validate Domain

if (
                    !/^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$/i.test(values.domain)
                  ) {
                    errors.domain = 'Invalid domain'
                  }

Validate Phone number

if (!values.phone_number) { errors.phone_number = 'Required'; } else if (!/^((\+[1-9]{1,4}[ \-])|(\([0-9]{2,3}\)[ \-])|([0-9]{2,4})[ \-])?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/.test(values.phone_number)) { errors.phone_number = 'The phone number is not correct'; }

Formik on form inpute change

const onEmailChange = (e, setFieldValue) => {
  const domain = e.target.value.replace(/.*@/, '')
  setFieldValue('mail.email', e.target.value)
  setFieldValue('mail.domain', domain, false)
}

Conditional Class

lastName={`banner ${active ? "active" : ""}

i18Next not working with react lazy properly

Disable the suspense in every component.

const { t } = useTranslation(['dashboard'], { useSuspense: false });

NextJS i18n workaround

Trans component not working properly

Provide the translation namespace properly

<Trans t={t} i18nKey="translation.msg">
</Trans>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment