0

Here I have form data. I have to push that data into an array. And the same time I have to retrieve that data and will show in another component.

import React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import { Link } from 'gatsby';
import DisplayOutput from '../pages/DisplayOutput';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

class DialogFormWithFormik extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false,
      userName: '',
      password: '',
      data:'',
      dialogModal: 'none',
    }
  }

  handleClickOpen = () => {
    this.setState({ open: true })
    this.setState({ dialogModal: 'login' })
  }
  handleRegisterClickOpen = () => {
    this.setState({ open: true })
    this.setState({ dialogModal: 'register' })
  }

  handleClose = () => {
    this.setState({ dialogModal: false })
  }
  handleUsernameChange = event => {
    this.setState({
      userName: event.target.value,
    })
  }
  handlePasswordChange = e => {
    this.setState({
      password: e.target.value,
    })
  }

  handleSubmit = () => {
    console.log(this.state.userName + '' + this.state.password)
    alert('values submitted')
  }

  form = props => {
    return (
      <div>
        <Button
          variant="outlined"
          color="primary"
          onClick={() => this.handleClickOpen()}
        >
          Login
        </Button>
        &nbsp;
        <Button
          variant="outlined"
          color="primary"
          onClick={() => this.handleRegisterClickOpen()}
        >
          Register
        </Button>
        <Dialog
          onClose={() => this.handleClose()}
          aria-labelledby="customized-dialog-title"
          open={this.state.dialogModal === 'login'}
        >
          <Form onSubmit={this.handleSubmit}>
            <DialogTitle id="form-dialog-title">
              To Display Student Data
            </DialogTitle>
            <TextField
              label="Username"
              type="text"
              margin="normal"
              name="userName"
              id="userName"
              onChange={this.handleUsernameChange}
              value={this.state.userName}
            />

            <br />
            <TextField
              label="Password"
              type="password"
              autoComplete="current-password"
              margin="normal"
              id="passsword"
              onChange={this.handlePasswordChange}
              value={this.state.password}
            />
            <br />

            <DialogActions>
              <nav>
                <Button variant="contained" type="submit" color="primary">
                  Login
                </Button>
              </nav>

              <br />
              <Button onClick={() => this.handleClose()}>Cancel</Button>
            </DialogActions>
          </Form>
        </Dialog>
      </div>
    )
  }
  schema = () => {
    const schema = Yup.object().shape({
      userName: Yup.string().required(),
      password: Yup.string().required(),
    })
    return schema
  }

  render() {
    return (
      <div className="Sample" align="center">
        <Formik render={this.form} />
      </div>
    )
  }
}

export default DialogFormWithFormik
0

2 Answers 2

1

In the method that handles the submit of the form, have the event as a parameter and call preventDefault Read more here. So the page doesn't reload when submitting. And then push the the data to the correct array.

handleSubmit = (event) => {
    event.preventDefault();
    ...
}
Sign up to request clarification or add additional context in comments.

8 Comments

Actually, my question was, when I will submit the form, the form values I should have to store in one array(like JSON). here I have to create one array object. after that, I have to retrieve the data from an array. can I display that array values in another component
I would use Redux/MobX/React Context for data-transport (in lack of a better word). React context Redux MobX
If i will use e.preventDefault(). the values are still in that field only. if we will clear the field data then only values are clear. but I don't want that. I want form should be there with the empty fields. and one thing. please read my first comment. I want to the solution for the above question.
If you would like the fields to be empty after the submit, you should have trigger a method that resets state-data after the submitting.
How can I save the form data(like userName and password) into an array?
|
1

Try this. I create for only one input field, and import and export your component as per your project file

state = {
  username: '',
  items:[]
};

handleFormSubmit = (e) => {

  e.preventDefault();
  let items = [...this.state.items];
  items.push({
    username: this.state.username
  });
  this.setState({
    items,
    username: '',
  });
};

handleInputChange = (e) => {
  this.setState({
    username: e.target.value
  })
}

render() {

  return (
    <>
      <div className="container">
        <form className='from-group ' onSubmit={this.handleFormSubmit}>

          <input className='form-control no-border input-field ' id="username" value={this.state.username} type="text" name="username" onChange={this.handleInputChange} required/>

          <div className="text-center">
            <button type='submit' className="mt-3 col-md-12 btn  btn-primary">ADD</button>
          </div>
        </form>
        <div className='mt-3'>
          <div className='center'>
            <table className="table table-dark table-hover">
              <tbody>
                <tr>
                  <th>Username</th>
                </tr>
                {this.items.map(item =>{ 
                return(
                  <tr>
                    <td>{item.username}</td>
                  </tr>
                  ); 
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  );
}
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.