Vishal Donga
Vishal Donga

Reputation: 25

How to display submitted form data in same page in Reactjs?

I am new in reactjs. I want to submit form data in same page in reactjs. I am using array to store data but array stores data in one-dimensional and I want it in multi-dimentional form. How can I do that? I am using push() function and there are 5 input field in my form. Here is my code:

    var data = [{}];
export default class Form extends React.Component {
  state = {
    firstName: "",
    lastName: "",
    username: "",
    email: "",
    password: ""
  };

  change = e => {
    this.props.onChange({ [e.target.name]: e.target.value });
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  onSubmit = e => {
    e.preventDefault();
    console.log(this.state);

    data.push(this.state.firstName,this.state.lastName,this.state.username,this.state.email,this.state.password);
    document.getElementById('hello').innerHTML = data;
};
render(){
//form  input fields
}
}

Thank You.

Upvotes: 0

Views: 4674

Answers (1)

Aseem Upadhyay
Aseem Upadhyay

Reputation: 4537

Set all your form data values in a state object.

Once, submitted you can set all those values in your state and then you can view the updated state with your form data in the render method.

Something on the lines of

handleSubmit(data) {this.setState({formData: data})}

And then in your render you can view it as

render() { console.log(this.state.formData); return(...); }

Manipulate this variable as you want it now. Care needs to be taken that this state will be null/empty/undefined as per your declaration before the first submit.

Upvotes: 2

Related Questions