반응형
axios
설치
yarn add axios
예제 - request
- get
import axios from 'axios';
axios.get('/api/get', {
params: {
id: 1234,
order: 'ASC',
}
}).then((response) => {
console.log('body', response.data);
})
- post
import axios from 'axios';
axios.post('/api/post', {
id: 1234,
}, {
headers: {
'Content-Type': 'application/json'
}
}).then((response) => {
console.log('body', response.data);
})
예제 - config
- default header
import axios from 'axios';
axios.defaults.headers.common = {
Pragma: 'no-cache',
debuggable: 'true',
}
- interceptor
import axios from 'axios';
axios.interceptors.request.use((requestConfig) => {
console.log('request success', requestConfig);
}, (error) => {
console.log('error', error)
});
axios.interceptors.response.use((response) => {
console.log('response success', response.data);
}, (error) => {
console.log('error', error)
});
참고
moment
설치
yarn add moment
예제
- 기본
import moment from 'moment';
const current = moment();
- string to moment
const result = moment('2000-01-01 23:59:59', 'YYYY-MM-DD HH:mm:ss');
- moment to string
moment('2000-01-01', 'YYYY-MM-DD').format('YYYY-MM-DD HH:mm:ss'); // '2000-01-01 00:00:00'
- add, subtract
moment('2019-12-01', 'YYYY-MM-DD').add(30, 'day'); // '2019-12-31'
moment('2019-12-31', 'YYYY-MM-DD').subtract(30, 'day'); // '2019-12-01'
- startOf, endOf
const theDate = moment('2019-06-06', 'YYYY-MM-DD'); // 6월 둘째 주 목요일
theDate.startOf('week'); // 6월 둘째 주 일요일
theDate.endOf('week'); // 6월 둘째 주 토요일
theDate.startOf('isoWeek'); // 5월 마지막 주 월요일
theDate.endOf('isoWeek'); // 6월 셋째 주 일요일
- isBefore, isAfter
const date1 = moment('2019-06-06 12:30:00', 'YYYY-MM-DD HH:mm:ss');
const date2 = moment('2019-06-06 13:30:00', 'YYYY-MM-DD HH:mm:ss');
date1.isBefore(date2); // true
date1.isAfter(date2); // false
date1.isBefore(date2, 'day'); // false
date1.isAfter(date2, 'day'); // false
date1.isSameOrBefore(date2); // true
date1.isSameOrAfter(date2); // false
date1.isSameOrBefore(date2, 'day'); // true
date1.isSameOrAfter(date2, 'day'); // true
날짜 단위
- "year", "years", "y"
- "month", "months", "M"
- "week", "weeks", "w"
- "day", "days", "d"
- "hour", "hours", "h"
- "minute", "minutes", "m"
- "second", "seconds", "s"
- "millisecond", "milliseconds", "ms"
참고
moment-timezone
설치
yarn add moment-timezone
예제
- 기본
import moment from 'moment-timezone';
const current = moment();
- 브라우저 time zone 알아내기
moment.tz.guess();
moment.tz.guess(true); // without caching
- default time zone 설정하기
moment.tz.setDefault();
moment().format('YYYY-MM-DD HH:mm:ss'); // 현재 브라우저 시간
moment.tz.setDefault('America/New_York');
moment().format('YYYY-MM-DD HH:mm:ss'); // 현재 뉴욕 시간
- time zone에 맞춰 시간 계산하기
const defaultFormat = 'YYYY-MM-DD HH:mm:ss';
const koreanTime = '2020-06-06 12:00:00';
const koreanDate = moment.tz(koreanTime, defaultFormat, 'Asia/Seoul'); // '2020-06-06 12:00:00'
const bangkokDate = koreanDate.tz('Asia/Bangkok'); // '2020-06-06 10:00:00'
참고
react-datetime
설치
yarn add moment react-datetime
예제
- App.css
.rdtDay {
text-align: center;
}
.rdtOld,
.rdtNew {
opacity: 0.2;
}
.rdtDisabled {
cursor: not-allowed;
opacity: 0.6;
}
.rdtActive {
background: skyblue;
color: white;
}
- App.js
import './App.css';
import 'moment/locale/ko';
import React, { useState, useCallback } from 'react';
import DateTime from 'react-datetime';
import moment from 'moment';
const App = () => {
const [time, setTime] = useState(moment('2020-06-06', 'YYYY-MM-DD'));
const isValidDate = useCallback((currentDate) => {
return currentDate.isSameOrAfter(
moment('2020-06-05', 'YYYY-MM-DD'),
'day'
);
}, []);
const renderDay = useCallback((props, currentDate, selectedDate) => {
return <td {...props}>{currentDate.date()}</td>;
}, []);
const renderMonth = useCallback((props, month, year, selectedDate) => {
return <td {...props}>{month}</td>;
}, []);
const renderYear = useCallback((props, year, selectedDate) => {
return <td {...props}>{year % 100}</td>;
}, []);
return (
<DateTime
className={'date-time'}
viewMode={'days'}
locale={'ko'}
input={false}
dateFormat={true}
timeFormat={false}
value={time}
onChange={setTime}
isValidDate={isValidDate}
renderDay={renderDay}
renderMonth={renderMonth}
renderYear={renderYear}
/>
);
};
export default App;
주의사항
-
locale 정보를 활요하기 위해서 moment locale 정보를 import해서 사용해야함
import 'moment/locale/ko';
-
create-react-app으로 생성한 프로젝트에서는 아래와 같은 설정때문에 자동으로 locale 정보를 로딩하지 못하기 때문
// webpack.config.js new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
참고
react-datetime-range-picker
설치
yarn add moment react-datetime react-datetime-range-picker
예제
- App.js
import 'moment/locale/ko';
import React, { useState } from 'react';
import DatetimeRangePicker from 'react-datetime-range-picker';
import moment from 'moment';
const DATE_FORMAT = 'YYYY-MM-DD';
const App = () => {
const [date, setDate] = useState({
startDate: moment('2020-06-06', DATE_FORMAT),
endDate: moment('2020-06-15', DATE_FORMAT)
});
return (
<DatetimeRangePicker
className={'datetime-range-picker'}
locale={'ko'}
viewMode={'days'}
dateFormat={'YYYY-MM-DD'}
timeFormat={false}
closeOnSelect={true}
startDate={date.startDate}
endDate={date.endDate}
onStartDateChange={(startDate) => setDate({ ...date, startDate })}
onEndDateChange={(endDate) => setDate({ ...date, endDate })}
isValidStartDate={(startDate) =>
startDate.isAfter(moment('2020-06-05', DATE_FORMAT))
}
isValidEndDate={(endDate) =>
endDate.isBefore(moment('2020-06-22', DATE_FORMAT))
}
/>
);
};
export default App;
주의사항 - 1
- viewMode='years'일 경우 성능이 잘 나오지 않으므로 주의 필요
- startDate ~ endDate 까지의 각 연도별 365일을 모두 돌며 isValidXXXDate() 함수를 호출해서 체크하는 로직에서 많은 연산을 하는 것이 원인
주의사항 - 2
- 다른 연도의 날짜를 startDate, endDate로 선택할 경우 range가 연결된 스타일로 올바르게 작동하지 않음
- 선택된 기간 내에 있는지 스타일을 체크하는 로직에서 월/일만 체크하고 연도는 체크하지 않아 올바르게 클래스가 먹지 않는 것이 원인
참고
react-player
설치
yarn add react-player
예제
- App.js
import React from 'react';
import ReactPlayer from 'react-player';
const App = () => {
return (
<React.Fragment>
<ReactPlayer
url="http://sample.vodobox.net/skate_phantom_flex_4k/skate_phantom_flex_4k.m3u8"
playing={true}
controls={true}
/>
<ReactPlayer
url="https://www.youtube.com/watch?v=5wqCB5XAa3c"
playing={true}
controls={true}
/>
</React.Fragment>
);
};
export default App;
참고
react-beautiful-dnd
설치
yarn add react-beautiful-dnd
예제
import React, { useCallback, useState } from 'react';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
const App = () => {
const [list, setList] = useState([
{ value1: 'AAA-0', value2: 'BBB-0' },
{ value1: 'AAA-1', value2: 'BBB-1' }
]);
const reorder = useCallback((list, fromIndex, toIndex) => {
const newList = Array.from(list);
const [removed] = newList.splice(fromIndex, 1);
newList.splice(toIndex, 0, removed);
return newList;
}, []);
const handleDragAndDrop = useCallback(
({ destination, source }) => {
if (!destination || destination.index === source.index) {
return;
}
setList(reorder(list, source.index, destination.index));
},
[list]
);
const cellStyle = useCallback((isDragging) => {
return isDragging ? { width: 100 } : undefined;
}, []);
return (
<table>
<colgroup>
<col width={100} />
<col width={100} />
<col width={100} />
<col width={100} />
</colgroup>
<thead>
<tr>
<th>column1</th>
<th>column2</th>
<th>column3</th>
<th>column4</th>
</tr>
</thead>
<DragDropContext
onDragEnd={handleDragAndDrop}
onDragStart={() => console.log('onDragStart')}
>
<Droppable droppableId={'list'}>
{(droppableProvider) => (
<tbody
ref={droppableProvider.innerRef}
{...droppableProvider.droppableProps}
>
{list.map((item, index) => (
<Draggable
key={index}
index={index}
draggableId={`item-${index}`}
>
{(draggableProvider, draggableSnapshot) => (
<tr
ref={draggableProvider.innerRef}
{...draggableProvider.draggableProps}
className={
draggableSnapshot.isDragging
? 'dragging'
: undefined
}
>
<td
style={cellStyle(
draggableSnapshot.isDragging
)}
>
{index}
</td>
<td
style={cellStyle(
draggableSnapshot.isDragging
)}
>
{item.value1}
</td>
<td
style={cellStyle(
draggableSnapshot.isDragging
)}
>
{item.value2}
</td>
<td
style={cellStyle(
draggableSnapshot.isDragging
)}
{...draggableProvider.dragHandleProps}
>
==
</td>
</tr>
)}
</Draggable>
))}
{/* droppableProvider.placeholder가 없으면 오류 발생 */}
{droppableProvider.placeholder}
</tbody>
)}
</Droppable>
</DragDropContext>
</table>
);
};
export default App;
참고
echarts-for-react
설치
yarn add echarts echarts-for-react
예제
import React, { useCallback, useMemo, useRef } from 'react';
import ReactEcharts from 'echarts-for-react';
const App = () => {
const ref = useRef();
const option = useMemo(() => {
return {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
crossStyle: {
color: '#999'
}
}
},
legend: {
data: ['蒸发量', '降水量', '平均温度']
},
xAxis: [
{
type: 'category',
data: ['4月', '5月', '6月', '7月', '8月', '9月'],
axisPointer: {
type: 'shadow'
}
}
],
yAxis: [
{
type: 'value',
name: '水量',
min: 0,
max: 250,
interval: 50,
axisLabel: {
formatter: '{value} ml'
}
},
{
type: 'value',
name: '温度',
min: 0,
max: 25,
interval: 5,
axisLabel: {
formatter: '{value} °C'
}
}
],
series: [
{
name: '蒸发量',
type: 'bar',
data: [23.2, 25.6, 76.7, 135.6, 162.2, 32.6]
},
{
name: '降水量',
type: 'bar',
data: [26.4, 28.7, 70.7, 175.6, 182.2, 48.7]
},
{
name: '平均温度',
type: 'line',
yAxisIndex: 1,
data: [4.5, 6.3, 10.2, 20.3, 23.4, 23.0]
}
]
};
}, []);
const onChartReady = useCallback((chartsInstance) => {
console.log('chartsInstance', chartsInstance);
}, []);
const onEvents = useMemo(() => {
return {
rendered: () => console.log('rendered'),
finished: () => console.log('finished'),
legendselectchanged: (status) =>
console.log('legendselectchanged', status)
};
}, []);
const onClick = useCallback(() => {
console.log('chartsInstance', ref.current.getEchartsInstance());
}, [ref]);
return (
<div>
<ReactEcharts
ref={ref}
className={'bar-chart'}
style={{ width: '100%', height: '400px' }}
option={option}
lazyUpdate={true}
onChartReady={onChartReady}
onEvents={onEvents}
/>
<button onClick={onClick}>get echarts instance</button>
</div>
);
};
export default App;
option
- tooltip
- grid
- legend
- color[]
- xAxis[]
- yAxis[]
- series[]
참고
반응형
'Development > React' 카테고리의 다른 글
[React] redux-saga (0) | 2020.12.30 |
---|---|
[React] react-redux (0) | 2020.12.30 |
[React] react-testing-library (0) | 2019.12.29 |
[React] Enzyme (0) | 2019.12.28 |
[React] Setting (0) | 2019.09.08 |