Home > Blockchain >  Why isn't state being passed to child components?
Why isn't state being passed to child components?

Time:12-08

I'm trying to set authentication state depending on an HTTP response body. However, I am unable to pass isAuth's state to app()'s child components. Each time I call setIsAuth() from SignIn.js I receive a: TypeError: setIsAuth is not a function. What am I doing wrong?

app.js

function App() {
    const [isAuth, setIsAuth] = useState(false);

    return (
      <Router>
        <Switch>
          <Route path = "/signin" component={SignInPage} setIsAuth={setIsAuth} isAuth={isAuth} exact/>
        </Switch>
      </Router>
    );
}

export default App;

SignInPage.js

const SignInPage = ({setIsAuth}) => {
  return (
    <SignIn setIsAuth={setIsAuth}></SignIn>
  );
};

export default SignInPage;

SignIn.js

const SignIn = ({setIsAuth}) => {

  const {handleSubmit} = useForm({});

  const onSubmit => {
    setIsAuth(true)
  }

  return (
    <SomeComponent onClick={handleSubmit(onSubmit)}/>
  )
}

export default SignIn

CodePudding user response:

Route component only accepts props that are defined in react-router-dom. If you want to pass props to the component you are rendering, You should pass them directly or you can use context. To pass props that you want, you should use render prop instead of component prop. So this code changes:

<Route path = "/signin" component={SignInPage} setIsAuth={setIsAuth} isAuth={isAuth} exact/>

to this:

<Route path = "/signin" render={() => <SignInPage setIsAuth={setIsAuth} isAuth={isAuth} />} exact/>

Although this should work, it's better to use context in these cases, especially if you want to pass these props to several other components.

  • Related