I have a small react app. in the app, I have a login form.
I have 3 pages as seen in the router at App
component below.
The issue is that I can't access any URL beside the /
path.
If I try to enter /login
or /mechinasetup
I receive 404 error.
Now, in localhost it works great, I can enter all the paths but on the server, I can enter only to /
path.
If I enter a Link
to the main page it will take me to the login page.
I don't want to add to the main page a link to the login page, I want the user to be able to see the /login
by typing /login
.
in the login
and MechinaSetup
components I have a redirect script that checks the local storage and according to the value there it will redirect the user if needed (code below).
How can I to this redirect without using <Link>
?
import React, { Component } from 'react';
import { BrowserRouter , Route, Switch } from 'react-router-dom';
import Calc from './components/Calc';
import Login from './components/auth/Login';
import MechinaSetup from './components/adminarea/MechinaSetup';
import './App.css';
class App extends Component {
render() {
return (
<BrowserRouter basename="/calc">
<Switch>
<Route exact path="/" component={Calc} />
<Route path="/login" component={Login} />
<Route path="/mechinasetup" component={MechinaSetup} />
</Switch>
</BrowserRouter>
);
}
}
export default App;
in short, this is the function that should redirect the login page
redirectUser = auth => {
if (auth === false) {
this.props.history.push("/login");
}
};
I am using history.push
as suggested in this question:
Programmatically navigate using react router
entire components
login component - the redirect function called redirectUser
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Redirect, Link } from 'react-router-dom';
import {connect} from 'react-redux';
import { userLogedIn } from '../../actions';
import {
Button,
Form,
FormGroup,
FormControl,
Col,
Checkbox,
ControlLabel,
HelpBlock,
Container,
Row
} from 'react-bootstrap';
class LoginForm extends Component {
state={
username: '',
password: '',
data: [],
auth: false
}
componentWillMount(){
const auth = localStorage.getItem('auth');
localStorage.getItem('auth') === 'true' ?
this.props.userLogedIn(this.props): console.log('xxx');
}
componentDidUpdate(){
this.redirectUser(this.props.user.auth);
}
onSubmitLogin = (event) => {
// let auth = this.state.auth;
event.preventDefault();
fetch('./api/user_switch/' + this.state.username +
'/'+ this.state.password )
.then(response => response.json())
.then(json => {
if(json.count > 0)
{
this.props.userLogedIn(this.props)
}
})
.catch(error => console.log('parsing faild', error))
}
onChange(event){
this.setState({
[event.target.name]: event.target.value
})
}
redirectUser = (auth) =>{
if(auth === true){
localStorage.setItem('auth', true);
localStorage.setItem('username', this.state.username);
localStorage.setItem('password', this.state.password);
this.props.history.push("/mechinasetup");
}
}
render() {
return (
<Container id="LoginForm" className="align-middle" style={loginForm}>
<h1 className="text-center">כניסה לניהול מחשבון מכינה</h1>
<Row className="show-grid justify-content-center">
<Col xs={8}>
<Form>
<FormGroup controlId="formHorizontalusername">
<Col xs={12} componentclass={'aa'} className="text-right">
דואר אלקטרוני:
</Col>
<Col xs={12}>
<FormControl
ref="username"
name="username"
type="text"
onChange={this.onChange.bind(this)}
placeholder="הקלד דואר אלקטרוני"/>
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword" >
<Col xs={12} componentclass={'cc'} className="text-right">
סיסמא:
</Col>
<Col xs={12}>
<FormControl ref="password" name="password" type="password" onChange={this.onChange.bind(this)} placeholder="הקלד סיסמא"/>
</Col>
</FormGroup>
<FormGroup>
<Col >
<Button onClick={this.onSubmitLogin} type="submit" className="full-width-btn" id="loginSubmit" block>התחבר</Button>
</Col>
</FormGroup>
</Form>
</Col>
</Row>
</Container>
);
}
}
const loginForm = {
height: '100vh'
}
const mapStateToProps = (state) =>{
return{
user: state.user
}
}
const mapDispatchToProps = dispatch => {
return {
userLogedIn: (params) => dispatch(userLogedIn(params))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
MechinaSetup Component- the redirect function called redurectUser
import React, { Component } from "react";
import { connect } from "react-redux";
import {
Container,
Form,
Button,
Col,
Row,
Table,
striped,
bordered,
hover
} from "react-bootstrap";
import { logOut, addCourse } from "../../actions";
import Courses from "./AdminCourses";
import Head from '../layout/Header';
class MechinaSetup extends Component {
state = {
id: Math.random(),
courseName: '',
courseWeeklyHours: '',
courseType: false
};
redirectUser = auth => {
if (auth === false) {
this.props.history.push("/login");
}
};
onChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
render() {
const headerTitle = 'מחשבון מכינה';
const Logout = true;
return (
<div>
<Head headerTitle={headerTitle} isLogOut={Logout}/>
{/* if user is not logged in redirect him to login page */}
{this.redirectUser(this.props.user.auth)}
<Courses />
</div>
);
}
}
const mapStateToProps = state => {
return {
user: state.user,
courses: state.courses
};
};
export default connect(
mapStateToProps,
{ logOut }
)(MechinaSetup);