react component names must start with an uppercase letter. react hook names must start with the word "use".
가끔 react
로 작업을 하다보면 위와 같은 오류를 마주칠 때가 있다. 이러한 오류가 나는 이유와 해결법에 대해 정리해보록 하자
위 에러가 발생하는 원인은 리액트 hooks
는 반드시 리액트 컴포넌트 안에서
선언되어야하는 규칙
을 어겼기 때문이다. 리액트는 대문자로 시작하는 태그를 리액트 컴포넌트로 인식하고 소문자로 시작하는 태그를 HTML 태그로 인식한다.
function notWorking(){
const [state , setState] = React.useState(false)
return (
<div>it's not working</div>
)
}
function Working(){
const [state , setState] = React.useState(true)
return (
<div>it's working</div>
)
}
위 두 컴포넌트에서 첫번째 notWorking
컴포넌트는 HTML 태그로 인식하기에 위 오류가 발생한다.
하지만 두번째처럼 리액트 컴포넌트로 처리를 하면 hooks를 사용할 수 있다.
사실 내가 이걸 정리하는 첫번째 이유는 material UI때문이다. material UI에서 renderCell은 HTML 태그로 인식하기 renderCell 안 함수에서 hooks
사용이 불가능하다.
그렇기에 한번 더 분리를 해서 처리해줘야한다.
const CultivatedAreaReporterListDialogColumnsButton = () =>{
const setOpen = useSetRecoilState(CultivatedAreaRepoterList);
const onClick = (e: any) => {
setOpen(false);
};
return (
<Button onClick={onClick} variant="contained" sx={{ width: "100px" }} color="warning">
선택
</Button>
)
}
export const CultivatedAreaReporterListDialogColumns: GridColDef[] = [
...usersInfo,
{
field: "modify",
headerName: "수정",
headerAlign: "center",
sortable: false,
flex: 0.3,
renderCell: (params) => {
return (
<CultivatedAreaReporterListDialogColumnsButton />
);
}
}
];
대충 이런식으로 하면 된다.