Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect user to another page after submit the form?

I want to redirect the user after submit the form in react JavaScript, example when user submit the form he/she redirect to google.com or some other URL with he/she information what he/she entered in the input filed. I created simple with one filed and submit button.

Here my sample code

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class App extends Component {
  state = {
    firstName: '',
    showName: false
  }
  inputHandler = (e) => {
    let updatedName = e.target.value;
    this.setState({ firstName: updatedName });
    //console.log(updatedName);  
  }
  onSubmitHandler = (e) => {
    e.preventDefault();
    this.setState({
      showName: true
    });
  }
  render() {
    return (
      <div>
        <form
          onSubmit={this.onSubmitHandler}>
          <label>Enter the Name</label>
          <input type="text"
            name="firstName" onChange={this.inputHandler} value=
            {this.state.firstName} />
          <button type="submit" onClick={this.onSubmitHandler}>Submit</button>
          {this.state.showName && <p>"FirstName: " {this.state.firstName}</p>}
        </form>
      </div>
    );
  }
}
export default (App);
like image 891
Raj Avatar asked Mar 05 '23 05:03

Raj


1 Answers

You can redirect using the this.props.history.push method.

  onSubmitHandler = (e) => {
    e.preventDefault();
   this.props.history.push('/dashboard')
  }
like image 147
Mohammad Raheem Avatar answered May 02 '23 00:05

Mohammad Raheem