프로젝트로 정리하는 리액트(2)

이동건 (불꽃냥펀치)·2025년 3월 9일

'/new' 새로운 일기 작성 페이지

New 페이지

  • /new url이 전달되면 해당 페이지로 이동
const New =()=>{
    const {onCreate} = useContext(DiaryDispatchContext);
    const nav = useNavigate();
    const onSubmit=(input)=>{
        onCreate(input.createdDate.getTime(),input.emotionId,input.content);
    }
    return(
        <div>
            <Header title={'새 일기 쓰기'} leftChild={<Button text={"< 뒤로 가기"} onClick={()=>{
                nav(-1);
            }}></Button>}></Header>
            <Editor onSubmit={onSubmit}></Editor>
        </div>
    )
    
}
  • Header,Editor 컴포넌트로 url 호출 후 새로운 일기장을 작성하기 위한 페이지 만듦
  • 해당 페이지에서는 Header를 사용해 이전페이지로 이동할 수 있게 childButton을 넣음

Editor

const emotionList=[
    {
        emotionId:1,
        emotionName:'완전좋음'
    },
    {
        emotionId:2,
        emotionName:'좋음'
    },
    {
        emotionId:3,
        emotionName:'그럭저럭' 
    },
    {
        emotionId:4,
        emotionName:'나쁨'
    },
    {
        emotionId:5,
        emotionName:'끔찍'
    }
];
const getStringedDate=(targetDate)=>{
    let year= targetDate.getFullYear();
    let month= targetDate.getMonth()+1;
    let date= targetDate.getDate();
    if(month<10){
        month=`0${month}`;
    }
    if(date<10){
        date=`0${date}`;
    }
    return `${year}-${month}-${date}`;
}
const Editor=({onSubmit})=>{
    const nav=useNavigate();
    const[input,setInput]=useState({
        createdDate:new Date(),
        emotionId:3,
        content:""
    });

    const onClickSubmit=()=>{
        onSubmit(input);
    }

    const onChangeInput=(e)=>{
        let name=e.target.name;
        let value=e.target.value;
        if(name==='createdDate'){
            value= new Date(value);
        }
        setInput({...input,[name]:value});

    }
  
    return(
        <div>
            <section>
                <h4>오늘의 날짜</h4>
                <input type="date" name="createdDate" id="" value={getStringedDate(input.createdDate)} onChange={onChangeInput}/>
            </section>
            <section>
                <h4>오늘의 감정</h4>
                <div>
                    {emotionList.map((item)=> <EmotionItem key={item.emotionId}{...item} isSelected={item.emotionId===input.emotionId} onClick={()=>onChangeInput({
                        target:{
                            name:'emotionId',
                            value:item.emotionId
                        }
                    })}></EmotionItem> )}
                </div>
            </section>
            <section>
                <h4>오늘의 일기</h4>
                <textarea name="content" id="" value={input.content} onChange={onChangeInput} placeholder="오늘은 어땟나요? "></textarea>
            </section>
            <section>
                <Button text={'취소하기'} onClick={()=>{
                    nav(-1);
                }}></Button>
                <Button onClick={()=>{
                    onClickSubmit();
                    nav(-1,{replace:true})
                }} text={'작성완료'}></Button>
            </section>
        </div>
    )
}

export default Editor
  • getStringedData: input값을 변환해서 xxxx-xx-xx 형식이 되게 만듦
  • onChangeInput: [name]으로 동적으로 객체값을 전달하게 만듦
  • name은 이벤트 객체의 name값을 가지고 오게 함
  • 감정 정보가 담긴 리스트를 map을 사용해 리스트의 숫자만큼 EmotionItem을 반환하게 함
  • 이때 EmotionItem에서는 리스트로 돌고 있는 감정 아이디와 현재 자신이 작성한 일기장의 감정 아이디가 같은지 여부를 전달하는 isSelected 프롭스를 전달받음
  • item을 클릭하면 감정 아이디를 해당 item의 감정 아이디로 변경하는 onClick

EmotionItem

const EmotionItem=({emotionId,emotionName,isSelected,onClick})=>{
    console.log(isSelected);
    return(
        <div className={`EmotionItem ${isSelected ? `EmotionItem_on_${emotionId}`:""}` } tabIndex="0"  onClick={onClick}>
            <img className='emotion_img' src={getEmotionImage(emotionId)} alt="" />
            <div className='emotion_name'>
                {emotionName}
            </div>
        </div>
    )
}
  • 전달 받은 프롭스를 근거로 다른 css를 적용하기 위해 동적으로 className 지정
  • getEmotionImageimport하여 감정 아이디에 맞는 이미지 호출
profile
자바를 사랑합니다

0개의 댓글