TIL | 최신순 정렬 - sort(), styled-reset ...

·2023년 7월 23일

TIL # WIL

목록 보기
32/65

23.07.21

1. 최신순 정렬 - sort()

sort() : 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환, 정렬은 stable sort가 아닐 수 있음. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따름

댓글을 날짜(시간)를 기준으로 최신순으로 정렬하고자 했고 알아보니 sort 메서드로 간단하게 구현이 가능했다 !

 const newComment = [{
      uid: user.uid,
      userName: user.displayName,
      body,
      createdAt: dateFormat,
    }, 
    {
      uid: user.uid,
      userName: user.displayName,
      body,
      createdAt: dateFormat,
    }
    ];

// 최신순 정렬
newComment.sort(function (a, b) {
  return new Date(b.createdAt) - new Date(a.createdAt);
})

// 오래된순 정렬
newComment.sort(function (a, b) {
  return new Date(a.createdAt) - new Date(b.createdAt);
})

기본적으로 유니코드 코드 포인트를 따른다고 하니 숫자나 날짜뿐만 아니라 가나다 순도 가능하다 !

mdn 문서
참고 블로그


2. styled-components와 styled-reset

기본적으로 브라우저마다 적용되어있는 css를 reset하기 위해 reset.css를 하곤했는데
리액트 라이브러리에도 styled-reset이 있었고 알고보니 이를 styled-components의 global style에 한 번에 간편하게 적용이 가능했다 !

우선 아래 2가지 중 1가지 방법으로 styled-comonents 와 styled-reset을 설치해야함
npm i styled-components styled-reset or yarn add styled-components styled-reset


그리고 나서 이렇게 GlobalStyle.js에 아래처럼 적어주면 css reset도 가능하고 전역적으로 적용할 수 있는 style도 같은 파일 내에서 작성할 수 있다 !
import {createGlobalStyle} from "styled-components";
import reset from "styled-reset";

const GlobalStyle = createGlobalStyle`
${reset}

body {
	width: 1200px
    font-size: 16px
    .
    .
    .
}

`;

export default GlobalStyle;

그리고 나면 GlobalStyle을 최상위 컴포넌트에 주입시켜야함 ! 최상위 컴포넌트는 바로 App.jsx !

import React from "react";
import Router from "./Router";
import GlobalStyle from "./GlobalStyle";

function App() {
  return (
    <>
      <GlobalStyle />
      <Router/>
    </>
  );
}

export default App;

이러면 바로 적용이 될 것이다 !

참고 블로그

1개의 댓글

comment-user-thumbnail
2023년 7월 23일

글 잘 봤습니다.

답글 달기