打田が実戦で使っているJavaScriptの便利関数を全て公開
Reactのプロジェクトで使っている便利関数を一気に公開します!
(随時更新)
僕はこれをhelpers.js
としておいて、各コンポーネントからimportしています。
使用例・import例(React.js)
import React, { useState, useEffect } from 'react
import * as H from '../../../helpers'
const ReactHooks(コンポーネント名) = (props) => {
useEffect(() => {
const validUrl = H.includeUrlPath(検証したいURL)
if(!validUrl){
window.location = '/404'
}
},[])
// 以下コンポーネントの中身...
}
export function formatDateTime(created_at) {
const date = new Date(created_at);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minutes = date.getMinutes();
return year + '/' + month + '/' + day + ' ' + hour + ':' + minutes;
}
if分岐でfalseを判定したい時に使うやつ(PHPっぽく動く)
export function isNullOrUndefinedOrZero(args) {
return args === undefined || args === null || args === '' || args === 0
}
export function isNullOrUndefined(args) {
return args === undefined || args === null || args === ''
}
export function isUndefined(args) {
return args === undefined;
}
export function birthChangeTextType(str) {
return str.replace(/[A-Za-z0-9]/g, function (s) {
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
});
}
export function iso8601ToDatetime(datetime, lng) {
const timezone = lng === 'jp' ? 'ja-JP' : 'es-US';
const dt = new Date(datetime);
const yyyy = dt.getUTCFullYear();
const mm = ('0' + (dt.getUTCMonth() + 1)).slice(-2);
const dd = ('0' + dt.getUTCDate()).slice(-2);
const date = yyyy + '/' + mm + '/' + dd;
return date;
}
export function equalUrlPath(path) {
if (window.location.pathname === path) {
return true;
} else {
return false;
}
}
export function includeUrlPath(path) {
if (window.location.pathname.indexOf(path) != -1) {
return true;
} else {
return false;
}
}