Route is not rendering component

459 Views Asked by At

Here is my code

index.js

import React from "react";
import ReactDOM from "react-dom";
import { Route, BrowserRouter } from "react-router-dom";

import Main from "./Main";
import registerServiceWorker from "./registerServiceWorker";

ReactDOM.render(
  <BrowserRouter>
    <Route exact path="/" component={Main} />
  </BrowserRouter>,
  document.getElementById("root")
);

registerServiceWorker();

Main.js

import React from "react";

import SelectList from "./SelectList";

class Main extends React.Component {
  state = {
    currentUser: "hello"
  };

  componentDidMount = () => {
    console.log("Main", this.props);
  };

  render() {
    return (
      <div>
        <h1>Hello world</h1>
        <SelectList
          currentUser={this.state.currentUser}
        />
      </div>
    );
  }
}

export default Main;

SelectList.js

import React, { Component } from "react";
import { Route, Switch, withRouter } from "react-router-dom";

import Welcome from "./Welcome";
import LoginForm from "./LoginForm";

class SelectList extends Component {
  componentDidMount = () => {
    console.log("SelectList", this.props);

    if (this.props.currentUser) {
      this.props.history.push({ pathname: "/welcome" });
    } else {
      this.props.history.push({ pathname: "/login" });
    }
  };

  render() {
    return (
      <div>
        <Switch>
          <Route exact path="/welcome" component={Welcome} />
          <Route exact path="/login" component={LoginForm} />
        </Switch>
      </div>
    );
  }
}

export default withRouter(SelectList);

Welcome.js

import React, { Component } from "react";

class Welcome extends Component {
  render() {
    return <p>Welcome</p>;
  }
}

export default Welcome;

LoginForm.js

import React, { Component } from "react";

class LoginForm extends Component {
  state = {
    emailOrMobile: "",
    password: ""
  };

  submitForm = () => {
    console.log("submit form");
  };

  componentDidMount = () => {
    console.log("hello world");
  };

  render() {
    return (
      <div>
        <form>
          Email or Mobile: <input type="text" /> <br />
          Password: <input type="password" /> <br />
          <input type="button" onClick={this.submitForm} />
        </form>
      </div>
    );
  }
}

export default LoginForm;

Here neither Welcome.js nor LoginForm.js is getting render. I have no clue what's wrong with my code. According to the render function of selection.js either one of the component LoginForm.js or Welcome.js must render. Here I am also defining currentUser in Main.js. If I will replace the componenetDidMunt with componentWillMount in SelectList.js then also its not working. Please also see the screenshot for the behaviour on my computer.enter image description here

0

There are 0 best solutions below