Patrick Youssef
Patrick Youssef

Reputation: 109

React Router - OnClick not processing in Navlink

At the bottom, in the NavLink tag, onClick does not work, I only get redirected to another page but it does not process the submitHandler function

If I remove the NavLink, then the submitHandler processes, but whenever I add a React Router tag, nothing fires

I remove most of the code because there were not essential to my question

class XXX extends React.Component {
  constructor() {
    super();
    this.state = {
      username: "",
      password: "",
      users: [],
      errors: []
    };
  }

  submitHandler = event => {
    event.preventDefault();

    let check = true;

    if (this.state.username == "") {
      this.showValidationErr("username", "Username cannot be empty !");
      check = false;
    }
    if (this.state.password == "") {
      this.showValidationErr("password", "Password cannot be empty !");
      check = false;
    }
    if (this.state.users.indexOf(this.state.username) != -1) {
      this.showValidationErr("username", "Username already exists !");
      check = false;
    }
    if (check) {
      axios
        .post("https://localhost:44314/api/Users", this.state)
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    }
  };

  render() {
    return (
      <div className="App">
        <form onSubmit={this.submitHandler}>
          <button type="Submit">
            <NavLink to="/newsfeed" onClick={() => this.submitHandler}>
              Create Account
            </NavLink>
          </button>
        </form>
      </div>
    );
  }
}

Upvotes: 3

Views: 984

Answers (1)

Hassaan Tauqir
Hassaan Tauqir

Reputation: 2722

You do not need the NavLink here, just use the button and the click will call the function used on the form.

<form onSubmit={this.submitHandler}> <button type="Submit" />Create Account</button> </form>

If you want to redirect, you can do it in the submitHandler function.

submitHandler = (event) => {
event.preventDefault();
// Your logic
this.props.history.push("newsfeed");

The history prop will be available when you wrap your component with withRouter HOF.

import { withRouter } from 'react-router-dom';

export default withRouter(YourComponent);

Upvotes: 4

Related Questions