개발공부/REACT

[React] 리뷰 - 별점 기능 만들기

sohee! 2024. 1. 28. 22:46

프로젝트에서 만드려고 하는 부분!

 

별 아이콘을 눌렀을 때, 해당 별점의 개수만큼 노란색 별로 바뀌게 하고, 오른쪽에 별점 개수를 출력하게 하는 기능을 만드려고 합니다!


1. svg 파일 저장 및 import 

 

피그마에서 가져온 svg 파일로 assets 폴더에 greyStar.svg, yellowStar.svg로 저장해놓고 import 해서 사용하였습니다.

 

 

사용하고자 하는 파일에서 yellowStar과 greyStar를 import 해서 가져옵니다.


2. 별점 변경 함수 & map() 함수 이용해 출력

    // 별점 기본값 설정
    const [clicked, setClicked] = useState([false, false, false, false, false]);
    // 별을 5개로 표현하기 위한 더미 배열 
    const array = [0, 1, 2, 3, 4]
    
    // 별점 변경 함수
    const starScore = index => {
        let star = [...clicked];
        for (let i = 0; i < 5; i++) {
            star[i] = i <= index ? true : false;
        }
        setClicked(star);
    };

 

별점 상태를 리스트 형태로 false, true로 구분하였습니다.

 

별이 클릭되었을 때 starScore(index) 형태의 함수가 실행되면서, 

클릭된 인덱스에 맞게 clicked 상태를 변경할 수 있도록 하였습니다!

 

{array.map((index) => (
            <img
              key={index}
              onClick={() => starScore(index)}
              src={clicked[index] ? yellowStar : greyStar} // clicked 배열이 true이면 yellowStar, false이면 greyStar을 출력
              alt = "starIcon"
            />))}

 

map() 함수를 이용해, 5개의 별이 출력되도록 하였고,

인덱스에 맞게 starScore(index) 함수가 실행되면서, clicked 상태의 배열이 true이면 yellowStar 이미지가, false이면 greyStar 이미지가 출력되도록 하였습니다. 

 


3. 별점 개수 구하기

    // 현재 선택한 별점 개수
    let clickedStarNum = clicked.filter(element => true === element).length;

 

filter 함수를 이용해 현재 선택된 별의 개수를 구합니다.


💻 전체 코드

//ReviewStars.jsx

import styled from "styled-components";
import React, {useState} from "react";
import yellowStar from "../../assets/recreation/yellowStar.svg";
import greyStar from "../../assets/recreation/greyStar.svg";

export default function ReviewStars() {
    // 별점 기본값 설정
    const [clicked, setClicked] = useState([false, false, false, false, false]);
    // 별을 5개로 표현하기 위한 더미 배열 
    const array = [0, 1, 2, 3, 4]
    
    // 별점 변경 함수
    const starScore = index => {
        let star = [...clicked];
        for (let i = 0; i < 5; i++) {
            star[i] = i <= index ? true : false;
        }
        setClicked(star);
    };

    // 현재 선택한 별점 개수
    let clickedStarNum = clicked.filter(element => true === element).length; 
  
    return (
    <>
    <ReviewStarstainer>
        <StarsWrap>
        {array.map((index) => (
            <img
              key={index}
              onClick={() => starScore(index)}
              src={clicked[index] ? yellowStar : greyStar} // clicked 배열이 true이면 yellowStar, false이면 greyStar을 출력
              alt = "starIcon"
            />))}
    </StarsWrap>
    </ReviewStarstainer>
    <StarNum>{clickedStarNum}/5</StarNum>
    </>
  );
}

const ReviewStarstainer = styled.div`
    display: flex;
    align-items: center;
    margin: 0px 20px;
`;

const StarsWrap = styled.div`
    width: 112px;
    display: flex;
    justify-content: space-between;
`;

const StarNum = styled.div`
    display: flex;
    align-items: center;
    color: #26282B;
    font-size: 20px;
    font-style: normal;
    font-weight: 400;
`

 

🎨 실제 구현 화면


📍 참고 링크

 

[React] 리뷰, 별점 기능구현하기

리뷰, 별점기능 구현하기

velog.io

 

[JS] 배열에서 특정 값 개수 구하기

📌 자바스크립트 배열에서 특정 값 개수 구하기 배열에서 특정 값의 개수를 구하는 방법에는 아래와 같은 방법이 있다. 반복문 filter( ) reduce( ) 1️⃣ 반복문 반복문을 사용해서 원하는 값이 나

cocobi.tistory.com