Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Redirect/go to the User Profile after login page in ReactJS

I am trying to Redirect to the User Profile page once the user is logged in with valid username and password

But when I click the Login button, it doesn't go to the User Profile (but it changes the url as intended (http://localhost:3000/instructor/banuka)

It should also display InstructorLoginFormComponent which it doesn't. When I click nothing happens but all I can see is still there is the login page

This is my InstructorLoginForm.jsx

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import InstructorProfile from "./instructor-profile";
import InstructorLoginFormComponent from "./instructor-login-form-component";

export default class InstructorLoginForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
      password: ""
    };

    this.onChangeUsername = this.onChangeUsername.bind(this);
    this.onChangePassword = this.onChangePassword.bind(this);
    this.handleOnClick = this.handleOnClick.bind(this);
  }

  onChangeUsername(e) {
    this.setState({
      username: e.target.value
    });
  }

  onChangePassword(e) {
    this.setState({
      password: e.target.value
    });
  }

  handleOnClick(e) {
    e.preventDefault();
    const path = `/instructor/${this.state.username}`;
    this.props.history.push(path);
  }

  render() {
    return (
      <Router>
        <Switch>
          <Route
            exact
            path="/login"
            component={props => (
              <InstructorLoginFormComponent
                {...props}
                username={this.state.username}
                password={this.state.password}
                handleOnClick={this.handleOnClick}
                onChangeUsername={this.onChangeUsername}
                onChangePassword={this.onChangePassword}
              />
            )}
          />
          <Route
            path={"/instructor/:instructorId"}
            component={InstructorProfile}
          />
        </Switch>
      </Router>
    );
  }
}

This is the InstructorLoginFormComponent.jsx

import React, { Component } from "react";
import { Link } from "react-router-dom";

export default class InstructorLoginFormComponent extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div className="container h-100" style={{ marginTop: 100 }}>
        <div className="d-flex justify-content-center h-100">
          <div className="user_card bg-dark">
            <div className="d-flex justify-content-center">              
            </div>
            <div
              className="d-flex justify-content-center form_container"
              style={{ marginTop: 0 }}
            >
              <form>
                <div className="input-group mb-3">
                  <div className="input-group-append">
                    <span className="input-group-text bg-info">
                      <i className="fa fa-user" />
                    </span>
                  </div>
                  <input
                    value={this.props.username}
                    onChange={this.props.onChangeUsername}
                    type="text"
                    name="username"
                    className="form-control input_user"
                    placeholder="username"
                  />
                </div>
                <div className="input-group mb-2">
                  <div className="input-group-append">
                    <span className="input-group-text bg-info">
                      <i className="fa fa-lock" />
                    </span>
                  </div>
                  <input
                    value={this.props.password}
                    onChange={this.props.onChangePassword}
                    type="password"
                    name="password"
                    className="form-control input_user"
                    placeholder="password"
                  />
                </div>
                <div className="form-group">
                  <div className="custom-control custom-checkbox">
                    <input
                      type="checkbox"
                      className="custom-control-input"
                      id="customControlInline"
                    />
                    <label
                      className="custom-control-label"
                      htmlFor="customControlInline"
                      style={{ color: "#ffffff" }}
                    >
                      Remember me
                    </label>
                  </div>
                </div>
              </form>
            </div>

            <div className="d-flex justify-content-center mt-3 login_container">
              <Link
                to={`/instructor/${this.props.username}`}
                type="button"
                className="btn login_btn bg-info"
              >
                Login
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

And this is the InstructorProfile.jsx

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

export default class InstructorProfile extends Component {
  render(){
      return(
          <div>
              <h1>Welcome to the profile</h1>
          </div>
      );
  }
}

Can someone please tell me where I have went wrong and suggest me a good way to redirect after login validation?

like image 808
Jananath Banuka Avatar asked Jan 18 '26 07:01

Jananath Banuka


1 Answers

Resolved As Is

The problems you're experiencing are likely related to your router not being configured correctly. If you want your InstructorLoginFormComponent to be rendered on path /, you have to put it inside the route like below. You cannot just pass the reference to the component since you need to pass it the username, password, etc props. You should remove it from anywhere else in your render function since you only want it to render when the path is /. I also changed your instructor path to use :id. When you want to specify a url parameter, you need to use the syntax /<my_url>:<my_variable_name>. It's important to put the / out front of all your paths because it's a relative path if you don't.

New Router Component

<Router>
  <Switch>
    <Route exact path="/login" render={props => (
      <InstructorLoginFormComponent
        {...props}
        username = { this.state.username }
        password = { this.state.password }
        handleOnClick = { this.handleOnClick }
        onChangeUsername = { this.onChangeUsername }
        onChangePassword = { this.onChangePassword }
      />
    )} />          
    <Route path={"/instructor/:instructorId"} component={InstructorProfile} />
  </Switch>
</Router>

Updated handleOnClick

handleOnClick(e) {
  e.preventDefault();
  const path = `/instructor/${this.state.username}`;
  this.props.history.push(path);
}

Updated Login Button

<Link
  to={`/instructor/${this.props.username}`}
  type="button"
  className="btn login_btn bg-info"
>
Login
</Link>

Recommendation Regarding Login

It's important to note that you aren't actually checking the username and password against something on the server. I'm not sure if this is your test code, or if you intend to implement something with REST. However, you should use a button instead of a link that calls a function on click that sends the username and password to the server. From there, it would return if the credentials matched and whether the user would be able to login or not. Then, you would use

this.props.history.push(`instructor/${this.state.username}`);

to forward the user to the instructor profile page. But you would only want to do that after you have checked their credentials. You would not use a Link component to perform those actions. I put an example below.

Example login button

<button
  type="button"
  className="btn login_btn bg-info"
  onClick={this.props.handleOnClick}
>
Login
</button>

New handleOnClick

handleOnClick = async (e) => {
  e.preventDefault();
  //pseudo-code below
  const user = await checkUserCredentialsAndGetUserObject(this.state.username, this.state.password);
  if(user.response === 'success') {
    this.setState({ user });
    this.props.history.push(`/instructor/${this.state.username}`);
  } else {
    flashMessage('The user credentials you entered were incorrect.');
  }
}
like image 188
technogeek1995 Avatar answered Jan 19 '26 19:01

technogeek1995



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!