Redux Thunk를 이용한 색상 선택기 구현 예제

이번 예제에서는 Redux Thunk를 사용하여 간단한 색상 선택기를 구현해보겠습니다. 이 예제는 React와 Redux를 기반으로 작성되며, 색상 선택 시 해당 색상을 Redux store에 저장하고, 선택한 색상을 화면에 표시하는 기능을 구현합니다.

설치 및 세팅

먼저, 프로젝트의 루트 디렉토리에서 다음 명령어를 실행하여 필요한 패키지들을 설치해주세요.

npm install react-redux redux redux-thunk

설치가 완료되면, Redux store를 생성하기 위해 store.js 파일을 생성하고 아래와 같이 내용을 작성해주세요.

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;

reducers.js 파일을 생성하고 아래와 같이 내용을 작성해주세요.

import { SET_COLOR } from './actionTypes';

const initialState = {
  selectedColor: '',
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case SET_COLOR:
      return {
        ...state,
        selectedColor: action.payload,
      };
    default:
      return state;
  }
};

export default rootReducer;

액션 타입 및 액션 생성자 생성

actionTypes.js 파일을 생성하고 아래와 같이 내용을 작성해주세요.

export const SET_COLOR = 'SET_COLOR';

actions.js 파일을 생성하고 아래와 같이 내용을 작성해주세요.

import { SET_COLOR } from './actionTypes';

export const setColor = (color) => ({
  type: SET_COLOR,
  payload: color,
});

컴포넌트 생성

ColorSelector.js 파일을 생성하고 아래와 같이 내용을 작성해주세요.

import React from 'react';
import { useDispatch } from 'react-redux';
import { setColor } from './actions';

const ColorSelector = () => {
  const dispatch = useDispatch();

  const handleColorChange = (e) => {
    dispatch(setColor(e.target.value));
  };

  return (
    <div>
      <label htmlFor="color-select">색상 선택:</label>
      <select id="color-select" onChange={handleColorChange}>
        <option value="">- 색상을 선택해주세요 -</option>
        <option value="red">빨강</option>
        <option value="green">초록</option>
        <option value="blue">파랑</option>
      </select>
    </div>
  );
};

export default ColorSelector;

ColorDisplay.js 파일을 생성하고 아래와 같이 내용을 작성해주세요.


import React from 'react';
import { useSelector } from 'react-redux';

const ColorDisplay = () => {
  const selectedColor = useSelector((state) => state.selectedColor);

  return (
    <div>
      <p>선택한 색상: {selectedColor}</p>
      <div
        style={{
          width: '100px',
          height: '100px',
          backgroundColor: selectedColor,
        }}
      ></div>
    </div>
  );
};

export default ColorDisplay;

App.js 수정

마지막으로, App.js 파일을 수정해주세요.

import React from 'react';
import ColorSelector from './ColorSelector';
import ColorDisplay from './ColorDisplay';

const App = () => {
  return (
    <div>
      <h1>색상 선택기</h1>
      <ColorSelector />
      <ColorDisplay />
    </div>
  );
};

export default App;

실행

이제 아래 명령어를 실행하여 예제를 실행해보세요.

npm start

실행된 서버에서는 http://localhost:3000으로 접속하여 색상 선택을 할 수 있습니다.


참조: