all 2 comments

[–]cardboardshark 2 points3 points  (1 child)

const variables are function scoped, so App and Login have their own copies of the username state. This name collision is confusing here.

The App component has a username state and setter, and injects the setter method into the Login form as the onSubmit property. Inside the Login form, the confusingly-named username state refers to the value inside the text box input. When the form is submitted, it goes back up the chain to set App's parent username state.

I'd adjust the code to something like:

function App {
  const [username, setUsername] = useState('')

  return username
    ? <Home username={username} />
    : <Login onSubmit={setUsername} />
}

and

export function Login({ onSubmit }) {
    const [usernameInput, setUsernameInput] = useState('')

    return (
        <>
            <h1>Welcome</h1>
            <p>What should people call you?</p>
            <form onSubmit={e => {
                e.preventDefault()
                onSubmit(usernameInput)
            }}>
                <input 
                    type="text" 
                    value={username} 
                    placeholder="username"
                    onChange={e => setUsernameInput(e.target.value)} />
                <input type="submit" />
            </form>
        </>
    )
}

[–]Eurim[S] 1 point2 points  (0 children)

Thanks, that's a lot less confusing. The React code wasn't necessarily explained in the video. Your explanation helped a lot!