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를 사용해 이전페이지로 이동할 수 있게 child에 Button을 넣음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의 감정 아이디로 변경하는 onClickEmotionItem
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 지정getEmotionImage를 import하여 감정 아이디에 맞는 이미지 호출