React에서 별점 드래그 구현하기

이원호·2023년 4월 13일
1

별점 드래그를 구현하기 위해 검색해본 결과 JS로 구현하는방법은 나와 있었으나 React로 구현하는 글을 찾기 어려워 JS로 구현한걸 참고하여 구현해보았다.

import React, { useEffect } from "react";
import { useState } from "react";

const Addr = () => {
  const [starCount, setStarcount] = useState(0);
  const starColor = starCount * 10 + "%";
  console.log(starCount);
  return (
    <div>
      <span className="star">
        ★★★★★
        <span>★★★★★</span>
        <input
          type="range"
          onMouseUp={(e) => setStarcount(e.target.value)}
          onTouchEnd={(e) => setStarcount(e.target.value)}
          step="1"
          min="0"
          max="10"
        />
      </span>
      <style jsx>{`
        .star {
          position: relative;
          font-size: 2rem;
          color: #ddd;
        }
        .star input {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          opacity: 0;
          cursor: pointer;
        }
        .star span {
          width: ${starColor};
          position: absolute;
          left: 0;
          color: red;
          overflow: hidden;
          pointer-events: none;
        }
      `}</style>
    </div>
  );
};

export default Addr;

한눈에 보기 쉽게 JSX를 사용했다.

생각보다 간단하다

input range와
빈 별 5개
빨간별 5개를 absolute로 겹친 뒤 드래그에 따라 빨간별의 width를 조정해주면 된다.

코드를 살펴보자면

 const [starCount, setStarcount] = useState(0);
 const starColor = starCount * 10 + "%";

로 state에 input의 드래그 값을 저장해준다

input의 드래그값 저장하는법

		<input
          type="range"
          onMouseUp={(e) => setStarcount(e.target.value)}
          onTouchEnd={(e) => setStarcount(e.target.value)}
          step="1"
          min="0"
          max="10"
        />

console을 찍으면 드래그 값이 찍히게 된다.

그리고 width 값을 %로 주려고 하기 때문에 드래그값 * 10 +"%" 를 작성하고
style 부분에 삽입하면 끝.

profile
정진하는개발자

0개의 댓글