Home > Software design >  Browserrouter redirect
Browserrouter redirect

Time:01-15

I'm new to react.js. This is my question. This line browserHistory.push("/Main") does not redirect to the main page after the successful login. Not sure the reason. Please help. I have already searched on the internet but couldn't find one to solve my problem. The URL address bar shows http://localhost:3000/Main but it does not redirect to the main page.

App.js

import React from "react"
import Login from "./Login"
import Main from "./Main"
import  {BrowserRouter as Router,Route,Switch}  from "react-router-dom"

function App() {
  
  return (
    <Router>
      <div className="App">

        <Switch>
          <Route exact path="/" component={Login}></Route>
          <Route path="/main" component={Main}></Route>
        </Switch>
          
      </div>
    </Router>
  )
  
}
export default App

APIService.js

import React, { Component } from 'react';
import { browserHistory } from 'react-router';

export default class APIService extends Component{
    

    static InsertData(body){
        return fetch("/login",{
            'method':'POST',
              cache: "no-cache",
              headers : { 
                'Content-Type': 'application/json'
                
               
      },
      body:JSON.stringify(body)
    })
    .then(response=>{
        if(response.ok){
            return response.json()
            }
        }
        
    ).then(
        data=>{
            if(data["isLogin"]===1){
              console.log(data)
              browserHistory.push("/main") // this line
            }
            
        }
    )
    .catch(error => console.log(error))
    }
}

login.js

import React, { useState} from "react";
import APIService from './ApiService'

function Login (){
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  
      const handleSubmit = (e) => {
        e.preventDefault()
        console.log(username)
        console.log(password)
        APIService.InsertData({username,password})
        
        setUsername('')
        setPassword('')
       
      }
    
    return (
      <div>
        
        <form className="form" onSubmit={handleSubmit}>
          
            <label htmlFor="username">UserName</label>
            <input type="text" name="username" placeholder="Enter your username:" value={username} onChange={(e)=>setUsername(e.target.value)}/>
       
          
            <label htmlFor="password">Password</label>
            <input type="password" name="password" placeholder="Enter your password:" value={password} onChange={(e)=>setPassword(e.target.value)}/>
          
            <button type="submit" >Login</button>
        </form>


      </div>
    );
  }


export default Login;

CodePudding user response:

Why dont use useHistory?

import { useHistory } from "react-router-dom";
history.push("/main");

CodePudding user response:

I made it work using. I am assuming that you used react-router-dom v5.

App.js

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Login from './Login';
import Main from './Main';

function App() {
    return (
        <Router>
            <div className='App'>
                <Switch>
                    <Route exact path='/' component={Login}></Route>
                    <Route path='/main' component={Main}></Route>
                </Switch>
            </div>
        </Router>
    );
}
export default App;

Login.js

import React, { useState } from 'react';

function Login({ history }) {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        \\ using timeout to simulate api call
        setTimeout(() => {
            history.push('/main');
        }, 2000);
    };

    return (
        <div>
            <form className='form' onSubmit={handleSubmit}>
                <label htmlFor='username'>UserName</label>
                <input
                    type='text'
                    name='username'
                    placeholder='Enter your username:'
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                />

                <label htmlFor='password'>Password</label>
                <input
                    type='password'
                    name='password'
                    placeholder='Enter your password:'
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                />

                <button type='submit'>Login</button>
            </form>
        </div>
    );
}

export default Login;

And Main.js

import React, { useState } from 'react';

export default function Main() {
    return (
        <div>
            <h1>Main Component</h1>
        </div>
    );
}

I would recommend you to not implement your API services this way. You should extend classes with Component unless they are React-Component. If you would like to group API services than you can create a folder called services and implement your services json there like services/auth.js, 'services/product.js'. And if you still want to use classes than don't extend them with Component class.

  •  Tags:  
  • Related