'Error while passing props through siblings

Here i'm passing props value from Navbar to Home and it works as expected, but the console shows error as: Cannot update a component ('App') while rendering a different component ('Home'). To locate the bad setState() call inside 'Home', follow the stack trace as described in https://reactjs.org/link/setstate-in-render and the error is shown in Home component as below.

function App(){
  const [login, setLogin] = useState(false);
  return(
    <Router>
      <Routes>
        <Route path="/Home" element={
          <>
            <Navbar login={login}/>
            <Home setlogin={setLogin}/>
          </>
        } />
      </Routes>
    </Router>
  );
};
export default App;

Navbar (Child 1)

function Navbar(login) {
  console.log(login);
}
export default Navbar;

Home (Child 2)

function Home(props) {
  if (condtion) {
    props.setlogin(true);  //showing error
  } else {
    props.setlogin(false);
  }
}
export default Home;


Solution 1:[1]

you're close! But you just have a few things muddled up.

The error message was alluding a setState that wasn't handled properly.

To change state via a function, passing from parent > child, for readability sake, I would create a function that handles it for you.

const handleLogin = (bool) => setLogin(bool);

Next, we hand that as a prop to pass down to the homepage component:

<Home handleLogin={handleLogin} />

Within the homepage component, we want to check for a "condition". Because React is reactive, we need to use the right tools to check if something has updated. For this example we need useEffect:

useEffect(() => {
  if (true) {
    handleLogin(true);
  } else {
    handleLogin(false);
  }
}, []);

In the Navbar component, you forgot to destructure the props so it wouldn't have worked anyway. Change this:

function Navbar(login) {

To this:

function Navbar({ login }) {

Check out this sandbox to see it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bopbopbop