I am new to react and I am just trying to create a simple form. When username and password are entered, and the submit button is clicked. I want a message to be displayed after the form containing username which is not working. Please help!
import './App.css';
import { Button, Container, Form } from 'react-bootstrap';
import { useState } from 'react';
function App() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [message, setMessage] = useState('')
function handleSubmit(event) {
event.preventDefault();
setMessage(<h1>{username}</h1>)
// console.log('message is ', message)
}
return (
<Container>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>
Username
</Form.Label>
<Form.Control value={username} onChange={(event) => {
setUsername(event.target.value)
console.log(username)
}} />
</Form.Group>
<Form.Group>
<Form.Label>
Password
</Form.Label>
<Form.Control value={password} onChange={(event) => {
setPassword(event.target.value)
console.log(password)
}} />
</Form.Group>
<Button className='mt-3'>Submit</Button>
</Form>
{message}
</Container>
)
}
export default App;
`
Two things you need to check:
Button
in your form should have a type="submit"
to trigger the form submission when clicked. return (
<Container>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Username</Form.Label>
<Form.Control
value={username}
onChange={(event) => setUsername(event.target.value)}
/>
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<Form.Control
type="password" // Ensure password input is hidden
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</Form.Group>
<Button type="submit" className='mt-3'>Submit</Button> {/* Ensure button triggers form submission */}
</Form>
{message && <h1>{message}</h1>} {/* Conditionally display the message */}
</Container>
);
}