리액트&타입스크립트

This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.

원코드 2023. 5. 3. 13:53

아래 코드와 같이 서버에서 전달된 데이터에 따라서 다른 html을 변수에 넣고 출력하려는데 에러발생

   .
   .
   .
   
   const projectList = (list: any) => {

        if(resCode == '0000') {

            const encData = list.map((data:any) => {
                return JSON.parse(data.encData)
            })

            return(
                <select id="projectList" onChange = {handleSelect} value={proIdx}>
                    {encData.map((pro:any) => {
                        return(
                            <option value="{pro[0].idx}" key="{pro[0].idx}">{pro[0].title}</option>
                        )
                    })}
                </select>
            )

        } else {
            return(
                <button id="projectList">프로젝트 생성</button>
            )
        }
    }

    return(
    .
    .
    .
                <div className="projectListDiv">
                    <label htmlFor="projectList" className="form-label">PROJECT</label>
                   {projectList}
                   /* ^^^^^^^
                    This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.
                   */
                </div>
    .
    .
    .

'~multiple children were provided.' 이 말때문에 <label> 을 없앴더니 다른 에러 발생

Type '(list: any) => JSX.Element' is not assignable to type 'ReactNode'.

 

결국 저 {projectList} 가 문제였던것

 

검색해서 projectList의 타입을 JSX.Element로도 해보고 ReactNode로도 해보다가 앞뒤로 빈 태그(<></>)를 붙이면 해결된다는 글을 봐서 붙였더니 리스트가 출력이 안됨 브라우저 콘솔 창에 아래 오류 발생함

Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

{projectList()} 이렇게 함수형식으로 선언하니 해결됨

<div className="projectListDiv">
    <label htmlFor="projectList" className="form-label">PROJECT</label>
   {projectList(list)}
</div>

 

 

 

참고한 블로그 

https://heytech.tistory.com/428

 

[React] 에러 해결: "Functions are not valid as a React child. This may happen if you return a Component instead of <Componen

❗️에러 상황 return에서 아래와 같이 코드 작성 후 실행 시 에러 발생 return ( {function} ) 📝에러 메시지 Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you

heytech.tistory.com