Home > OS >  How to make my form data appear on the console after I submit the form?
How to make my form data appear on the console after I submit the form?

Time:03-20

I am learning React. I have made the form using react-bootstrap. I was trying to output the data entered in my form to be displayed on the console when I submit the form. Upon submitting the form the data appears for a small-time span but then the page reloads and the console becomes blank.

Here is my code

import React, { Component } from 'react';
import classes from './Admin.css';
import { Form, Button, Container } from 'react-bootstrap';

class Admin extends Component {
    state = {
        content: null,
        category: null
    }


    onChangeContentHandler = (event) => {
        this.setState({ content: event.target.value });

    }

    onChangeCategoryHandler = (event) => {
        this.setState({ category: event.target.value });

    }

    onSubmitHandler=()=>{
        alert("Content: "  this.state.content "    Category: "  this.state.category);

    }


    render() {
        return (
            <Container className={classes.Body}>
            <Form onSubmit={this.onSubmitHandler}>
            <Form.Group className="mb-3" controlId="formBasicEmail">
              <Form.Label>Content</Form.Label>
              <Form.Control type="text" 
                            placeholder="Enter content" 
                            onChange={this.onChangeContentHandler}/>
              
            </Form.Group>
          
            <Form.Group className="mb-3" controlId="formBasicPassword">
              <Form.Label>Category</Form.Label>
              <Form.Control type="text" 
                            placeholder="Enter category" 
                            onChange={this.onChangeCategoryHandler}/>
            </Form.Group>
            
            <Button variant="primary" type="submit">
              Submit
            </Button>
          </Form>

            </Container>

        );
    }
}

export default Admin;

I am unable to detect why my page is reloading upon submittion. What should I do to not let my form data disappear from the console?

CodePudding user response:

Make your submitHandler function like this :

onSubmitHandler=(e)=>{
        e.preventDefault()
        alert("Content: "  this.state.content "    Category: "  this.state.category);

    }

The preventDefault function prevents the default action of reloading the website after the form submission.

  • Related