// 글자수 제한 함수
const checkTextLength = (e, maxLength, setLength) => {
let targetText = e.target.value;
let textLength = e.target.value.length;
if (textLength <= maxLength) setLength(e.target.value.length);
else {
e.target.value = targetText.substr(0, maxLength);
setLength(maxLength);
}
};
아래는 구현한 화면이다. 입력한 글자수대로 {length}/100에서 length 상태를 업데이트시켜주도록 했다.
textarea 태그안에는 자식태그를 넣을 수 없기 때문에, 바깥에 div로 감싸서 안에 p, textarea태그를 넣어서 마치 textarea처럼 보이게 컴포넌트를 구성했다.
// 드롭다운 state
const [isDown, setIsDown] = useState(false);
const [region, setRegion] = useState(isRegion);
...
<LocationBox>
<DropDownBox>
{isEdit ? (
!isDown && !region ? (
<SelectText>{isRegion}</SelectText>
) : (
<SelectText>{region ? region : isRegion}</SelectText>
)
) : (
<SelectText>{region ? region : "지역 선택"}</SelectText>
)}
<DropDownIcon
style={{ cursor: "pointer" }}
onClick={() => {
setIsDown(!isDown);
}}
/>
</DropDownBox>
<TextInput
height="48px"
width="calc((100% / 3) * 2)"
border="1px solid #999"
padding="14px 16px"
borderNone
ref={locationRef}
onChange={(e) => {
checkTextLength(e, 100, setLocationLength);
setPost({ ...post, location: e.target.value });
}}
placeholder="카페 위치 (ex. 홍대 어딘가)"
value={
post && post.location
? post.location.substr(
post.location.indexOf(" ") + 1,
post.location.length
)
: ""
}
/>
</LocationBox>
)}
{isDown && (
<RegionListBox>
{regionList.map((r) => (
<Region
key={r}
onClick={() => {
setRegion(r);
}}
>
{r}
</Region>
))}
</RegionListBox>
)}
request 데이터를 보낼 때는 "시도" + "상세위치" 를 같이 보내주고, 수정시에는 두 개를 나눠서 하나는 드롭박스안에, 하나는 textarea 안에 넣어줘야해서 여기서 시간이 좀 걸렸던 것 같다.
-> 자바스크립트 문자열 내장 메소드를 사용해서 해결했다. substr, indexOf
수정모드일 때 원래는 post.location.split(" ")[0]
이런 식으로 받아온 위치정보를 바로 보여줬는데 이렇게 하니까 location을 수정하면 onChange이벤트가 발생하면서, 드롭박스 안에 있는 위치정보도 바뀌게 되는 문제가 생겼다.
-> 아래 코드에서 처럼, region state의 초기 상태값을 수정모드 일 땐post.location.split(" ")[0]
로 지정하고, 아닐 땐 null로 지정해줘서 location이 변해도 영향을 받지 않도록 해주었다.
const isRegion = isEdit && post ? post.location.split(" ")[0] : null;
// 드롭다운 state
const [isDown, setIsDown] = useState(false);
const [region, setRegion] = useState(isRegion);