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;
`
4
Answers
Two things you need to check:
Button
in your form should have atype="submit"
to trigger the form submission when clicked.this part is wrong:
instead put:
and the Button should be type submit:
Issue:
It looks like the form is not being submitted because the button type is not set to submit. As a result, the form does not trigger the submit event, and you cannot see the message on the screen.
Solution:
Ensure that the button inside your form has the type attribute set to submit. This will trigger the form submission when the button is clicked. Here’s how you can fix it:
Explanation:
In HTML, the type attribute of a button determines its behavior. By default, a button has the type attribute set to button, which means it does not submit the form. Changing the type to submit makes the button act as a submit button, which will trigger the form submission and allow you to see the results or message on the screen.
If you are using a library like React Bootstrap or Material-UI, make sure that the component you are using is properly configured to handle the type attribute.
You can do something like this. I’d suggest read the documentation thoroughly before working: https://react.dev/learn