Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't state being passed to child components?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading