Skip to content

Commit

Permalink
refactor: Funnel Children 요소가 없는 경우, prev, next 함수의 방어코드 작성
Browse files Browse the repository at this point in the history
  • Loading branch information
bytrustu committed Mar 7, 2024
1 parent 3afad82 commit dfcd1cc
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/components/Funnel/Funnel.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import React, { createContext, useState, useMemo, PropsWithChildren, useContext } from 'react';
import { createContext, useState, useMemo, PropsWithChildren, useContext, Children } from 'react';

type FunnelContextType = {
currentIndex: number;
goToNext: () => void;
goToPrev: () => void;
};

export const FunnelContext = createContext<FunnelContextType | undefined>(undefined);
export const FunnelContext = createContext<FunnelContextType | null>(null);

type FunnelProps = PropsWithChildren<{
startIndex?: number;
}>;

export const Funnel = ({ children, startIndex }: FunnelProps) => {
const [currentIndex, setCurrentIndex] = useState(startIndex ?? 0);
const lastIndex = React.Children.count(children) - 1;
const lastIndex = Children.count(children) - 1;

const goToNext = () => {
if (lastIndex < 0) {
return;
}
setCurrentIndex((prevIndex) => (prevIndex >= lastIndex ? 0 : prevIndex + 1));
};

const goToPrev = () => {
if (lastIndex < 0) {
return;
}
setCurrentIndex((prevIndex) => (prevIndex <= 0 ? lastIndex : prevIndex - 1));
};

Expand All @@ -37,7 +42,7 @@ const FunnelStep = ({ index, children }: FunnelStepProps) => {

export const useFunnel = () => {
const context = useContext(FunnelContext);
if (!context) {
if (context === null) {
throw new Error('useFunnel은 Funnel.Root 하위에서 사용되어야 합니다.');
}
return context;
Expand Down

0 comments on commit dfcd1cc

Please sign in to comment.