0

I am having a problem accessing the props passed through the route to the child component. I am trying to get hold of the Authentication function in the App page , so that I can toggle it to true when my onLogin function in the Login page get the correct response. Any help will be highly appreciated.

please find the code below

//App.js

import React, { Component } from "react";

//import TopNavigation from './components/topNavigation';
//import { BrowserRouter, Route, Switch } from "react-router-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import MainPage from "./Mainpage";
import LoginPage from "./components/pages/LoginPage";
//import ProtectedRoute from "./protected.route";
import "./styleFiles/index.css";

class App extends Component {
  constructor() {
    super();
    this.state = {
      isAuthenticated: false
    };
    this.Authentication = this.Authentication.bind(this);
  }

  Authentication(e) {
    this.setState({ isAuthenticated: e });
  }

  render() {
    if (this.state.isAuthenticated === false) {
      return (
        <BrowserRouter>
          <div className="flexible-content ">
            <Route
              path="/login"
              render={props => <LoginPage test="helloworld" {...props} />}
            />
            <Route component={LoginPage} />
          </div>
        </BrowserRouter>
      );
    } else {
      return (
        <div className="flexible-content ">
          <Switch>
            <Route
              path="/"
              exact

              component={MainPage}
            />
            <Route component={MainPage} />
          </Switch>
        </div>
      );
    }
  }
}

export default App;
//login page

import React, { Component } from "react";
import logo from "../../assets/justLogo.svg";

import "../../styleFiles/loginCss.css";

class LoginPage extends Component {
  constructor(props) {
    super(props);
  }



  onLogin = event => {
    let reqBody = {
      email: "rpser1234@gmail.com",
      password: "rpser1234"
    };
    // event.preventDefault();
    fetch("http://localhost:8000/api/auth/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(reqBody)
    })
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error("Something went wrong with your fetch");
        }
      })
      .then(json => {
        localStorage.setItem("jwtToken", json.token);
        console.log(this.props.test);
      });
  };

  render() {
    const {
      test,
      match: { params } 
    } = this.props;
    console.log(test);
    return (
      <div className="bodybg">
        <div className="login-form">
          <div className="form-header">
            <div className="user-logo">
              <img alt="MDB React Logo" className="img-fluid" src={logo} />
            </div>
            <div className="title">Login</div>
          </div>
          <div className="form-container">
            <div className="form-element">
              <label className="fa fa-user" />
              <input type="text" id="login-username" placeholder="Username" />
            </div>
            <div className="form-element">
              <label className="fa fa-key" />
              <input type="text" id="login-password" placeholder="Password" />
            </div>
            <div className="form-element">
              <button onClick={this.onVerify}>verify</button>
            </div>

            <div className="form-element forgot-link">
              <a href="http://www.google.com">Forgot password?</a>
            </div>
            <div className="form-element">
              <button onClick={this.onLogin}>login</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default LoginPage;

I am trying to access the test prop from the loginPage but no success. Any idea were am I going wrong?

Riyesh
  • 43
  • 10

3 Answers3

1

Try this:

<Route
   path="/login"
   render={props => <LoginPage test={this.state.isAuthenticated} {...props} />}
/>

You have isAuthenticated not Authentication.

ravibagul91
  • 16,494
  • 4
  • 24
  • 45
Anil Kumar
  • 1,852
  • 1
  • 15
  • 20
  • I am trying to pass the Authentication function to LoginPage... so that I can use it in Loginpage to toggle the state.isAuthenticated value . even the isAuthenticated object is not accessible at the LoginPage.. dont no why – Riyesh May 08 '19 at 10:46
0

Your approach is not the best practice. For such purposes it is best to use redux + redux-thunk.

If you still want to go this way. You make mistake on here:

<Route
   path="/login"
   render={props => <LoginPage test={this.state.isAuthention} {...props} />}
/>

this.state.isAuthention replace on this.state.isAuthenticated After that you need send via props Authentication callback and call it's in fetch( ... ).then((result) => this.props.Authentication(result))

ravibagul91
  • 16,494
  • 4
  • 24
  • 45
  • my point is that I am not able to get the test value. for instance if I put ``` } />``` I am not able to access the test at all. when I try to console.log (this.props.test), I am getting a undefined in my browser console – Riyesh May 08 '19 at 10:56
  • @Riyesh [Look example](https://codesandbox.io/embed/4026kn7xo0) You can fork it and past your code. – Timofey Goncharov May 08 '19 at 11:13
0

You are using state to pass function as prop,

<Route
   path="/login"
   render={props => <LoginPage test={this.state.Authentication} {...props} />} //Wrong way to pass function as prop
/>

If you want to pass a function as prop use this, Ref

<Route
   path="/login"
   render={props => <LoginPage test={this.Authentication} {...props} />}
/>

If you want multiple routes for same component, then use exact attribute like this, check this

<Route 
  exact   //This will match exact path i.e. '/login'
  path="/login"
  render={props => <LoginPage test={this.Authentication} {...props} />}
/>
ravibagul91
  • 16,494
  • 4
  • 24
  • 45
  • forget about the authentication function ... I am trying to pass on ``` } /> ``` when I try to console.log (this.props.test), I am getting a undefined in my browser console – Riyesh May 08 '19 at 11:02
  • @Riyesh What does second route `` is doing? If it is not in use try to remove it. – ravibagul91 May 08 '19 at 11:10