jenlee123
jenlee123

Reputation: 153

Router changes the url but not the components rendered

Okay so when someone logs in, it should redirect him to the phones component. But from some reason it only changes the URL to /phones and doesnt render the component. I think it may be smth to do with the api I am using https://app.swaggerhub.com/apis/warp/etn-device-checker-test/1.0#/default/post_login where token might be required but not sure. Thanks for any advices.

Login.js

import React from 'react'
import axios from 'axios';
import { useState } from 'react';
import { useHistory } from "react-router-dom";
function Login() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    
   
    let history = useHistory()
    const onSubmit = (e) => {
      e.preventDefault();
      const getIn = {
      
        "login":email,
        "password":password,
        
    
      };
  
      
      axios
        .post('https://js-test-api.etnetera.cz/api/v1/login', getIn,
        {
            headers: {
                
                 'content-type': 'application/json', 
           }
        }).then((res) => {
      console.log(res.data); 
      history.push("/phones");
    })
        .catch((error) => console.log(error));
       
    };
    return (
        <div>
           <form >
         <label>email</label> <input value={email}
          onChange={(e) => setEmail(e.target.value)} type="text"/>
        <label>password</label>  <input type="text" value={password}
          onChange={(e) => setPassword(e.target.value)}/>
        <button onClick={onSubmit}>login</button>
           </form>
        </div>
    )
}

export default Login

app.js

import './App.css';
import Login from './Login';
import MobileList from './mobileList';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
function App() {
  return (
    <div className="App">
 <Router>
 <Switch>
 <Route>
<Login path='/login' exact/>
</Route>

 <Route>
 <MobileList path='/phones' exact/>
 </Route>
 
 </Switch>
 



 

 </Router>
 
    </div>
  );
}

export default App;

mobileList.js

import React from 'react'
import { MobileContext } from './MobileContext';
import { useContext } from 'react';
import Mobile from './Mobile';
function MobileList() {
    const { mobiles } = useContext(MobileContext);
    return (
        <div>
         {mobiles.map((item) => (
          <Mobile
           vendor={item.vendor}
          />
        ))}  
        hezasdccccccccccccccc 
        </div>
    )
}

export default MobileList

Upvotes: 0

Views: 26

Answers (1)

Josef Wittmann
Josef Wittmann

Reputation: 1339

You have to use the path prop on the Route, not on its children:

<Route path='/login' exact>
    <Login /> 
</Route>
<Route path='/phones' exact>
    <MobileList />
</Route>

Upvotes: 1

Related Questions