[React] React Router v6 - HOC 적용하기

FE.1·2022년 9월 14일
0
post-thumbnail

에러 발생 🚨

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

function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={Auth(LandingPage, null)} />
        <Route path="/login" element={Auth(LoginPage, false)} />
        <Route path="/register" element={Auth(RegisterPage, false)} /> */}
      </Routes>
    </div>
  );
}

React Router v6 부터 component={} 대신 element={} 를 사용해야 한다.
HOC 는 함수인데, element={}에는 함수가 들어갈 수 없기 때문에 발생하는 오류이다. 오로지 컴포넌트만 넣을 수 있다.


2가지의 해결책 🚀

1. 컴포넌트를 반환하는 함수로 만든 후 적용한다.

import Auth from "../hoc/auth"

function App() {
  const AuthLandingPage = Auth(LandingPage, null);
  const AuthLoginPage = Auth(LoginPage, false);
  const AuthRegisterPage = Auth(RegisterPage, false);

  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={ <AuthLandingPage /> } />
          <Route path="/login" element={ <AuthLoginPage /> }/>
          <Route path="/register" element={ <AuthRegisterPage /> } />
        </Routes>
      </Router>
    </div>
  );
}

2. HOC를 적용할 컴포넌트, export에 적용한다.

import Auth from "../hoc/auth"

const LandingPage = () => {
  return (
    {...}
  );
};

export default Auth(LandingPage, null);

[출처] https://velog.io/@nemo/router-error-v6-hoc

profile
공부하자!

0개의 댓글