Search code examples
reactjsreact-bootstrap

unable to change the value using setState


I am using React.js but I cannot achieve to change the value of my variable test.

Here is the code of App.js :

function App() {
  const [test, setTest] = useState(false);

  return (
    <div className="App">
      <myNavBar handleTest={(test) => setTest(test)} />
      <div>
          {test ? <Test/> : null}
      </div>
    </div>
  );
}

export default App;

And the code of myNavBar.js :

const myNavBar = (props) => {


    const handleTest = (value) => {
        props.handleTest(value);
    }
    return (
        <>
            <Navbar bg="white">
            <Navbar.Brand>Test</Navbar.Brand>
            <Nav>
              <Nav.Link href="/" onSelect={() => {handleTest(false)}}>Home</Nav.Link>
              <Nav.Link href="/test" onSelect={() => {handleTest(true)}}>Test</Nav.Link>
            </Nav>
            </Navbar>
        </>
    )
}

export default myNavBar;

I think I lost the modification of the value of test which is always equal to false

Could you help me please ?

Thank you very much !


Solution

    • Components must begin with an uppercase letter.

    • The code works, but when you click a link the page navigates. If you cancel the event it works as expected.

    https://codesandbox.io/s/react-playground-forked-yiqre?file=/index.js

    Nutshell:

    <Nav.Link
      href="/"
      onSelect={(_, e) => {
        e.preventDefault();
        handleTest(false);
      }}
    >
    

    Cleaned up, with the navigation in place:

    https://codesandbox.io/s/react-playground-forked-6vch3?file=/index.js

    You're trying to do an SPA, but it is not currently an SPA. You navigate away from the page with the updated state. When the new page loads (/test) your state resets.

    There's a variety of ways to create an actual SPA where you define a component per page: you can use any of several routing solutions, there are hook-based solutions, etc.

    Plus there's no /test path in the code sandbox so it wouldn't know what to do anyway.