3

When login button is clicked, console log output 'Redirecting..' is seen. But, the Welcome component is not seen. No errors are also logged.

import React, { useState } from 'react';
import  { Redirect } from 'react-router-dom'
import './App.css';
import { Form, Input, Button, Checkbox } from 'antd';

function App() {
  const bgstyle={
      background:"linear-gradient(to right, #11998e, #38ef7d)",
      height:"100vh",display: 'flex',  justifyContent:'center', alignItems:'center',flexDirection: 'column'
  }
  let isLoggedIn = useState(false)
  const onFinish= function onfinish(data){
    isLoggedIn = data.password=="password"?true:false
    if(isLoggedIn){
      console.log('Redirecting..')
      return <Redirect to='/Welcome/' />
    }
  }

  return (
    <div style={bgstyle}>
      <h1 style={{color:'white'}}>Welcome</h1>
      <Form onFinish={onFinish}>
        <Form.Item name="username" rules={[{ required: true, message: 'Please enter your username!' }]}>
          <Input placeholder="Username"/>       
        </Form.Item>

        <Form.Item name="password" rules={[{ required: true, message: 'Please enter your password!' }]}>
          <Input.Password placeholder="Password"/>       
        </Form.Item>

        <Button type="primary" style={{width:200,borderColor:'gray',background:'gray'}} htmlType="submit">Login</Button>
      </Form>
    </div>
  );
  }
export default App;

Welcome.js code:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    <p>Welcome</p>,
  document.getElementById('root')
);

Should I use Route? What am I missing? I am just beginning in react. Please post any links that may help me understand more.

2
  • Redirect is used to redirect the user to the specified route incase the user enters an invalid route in the search bar. One example could be you have a `<Route to='/home' /> and if the user mis-spells home he'll end up at an invalid route hence redirect is used to send the user to the 'default' route. In your case, you should use a Route
    – amogus
    Commented Aug 30, 2020 at 12:36
  • Use Navigate now...stackoverflow.com/questions/63690695/… Commented Mar 1, 2023 at 0:59

2 Answers 2

4

You should use history api from react-router-dom. You could access it with useHistory hook.

You could check this docs here

import React, { useState } from 'react';
import  { Redirect, useHistory } from 'react-router-dom'
import './App.css';
import { Form, Input, Button, Checkbox } from 'antd';

function App() {
  const bgstyle={
      background:"linear-gradient(to right, #11998e, #38ef7d)",
      height:"100vh",display: 'flex',  justifyContent:'center', alignItems:'center',flexDirection: 'column'
  }
 const history = useHistory();
  let isLoggedIn = useState(false)
  const onFinish= function onfinish(data){
    isLoggedIn = data.password=="password"?true:false
    if(isLoggedIn){
      console.log('Redirecting..')
      return history.push('/Welcome')    
  }

  return (
    <div style={bgstyle}>
      <h1 style={{color:'white'}}>Welcome</h1>
      <Form onFinish={onFinish}>
        <Form.Item name="username" rules={[{ required: true, message: 'Please enter your username!' }]}>
          <Input placeholder="Username"/>       
        </Form.Item>

        <Form.Item name="password" rules={[{ required: true, message: 'Please enter your password!' }]}>
          <Input.Password placeholder="Password"/>       
        </Form.Item>

        <Button type="primary" style={{width:200,borderColor:'gray',background:'gray'}} htmlType="submit">Login</Button>
      </Form>
    </div>
  );
  }
export default App;
1

What's happening in your code is basically that function is returning a react object but it's not rendering it, that's why you see console but no redirection happens. If you want this to work use if(isLooged) return outside the "onFinish" function. So it can Render on Dom and redirect successfully.

Also, You Have to define Routes as mentioned below if you want Redirect to work. Check the below code and set routes and login flow in the same way.

const [isLoggedIn, setLogin] = useState(false);

const onFinish = function onfinish(data){
    if(data.password === "password") setLogin(true);
}

if(isLoggedIn){
  console.log('Redirecting..')
  return <Redirect to='/Welcome' />
}
return (
<div style={bgstyle}>
  <h1 style={{color:'white'}}>Welcome</h1>
  <Form onFinish={onFinish}>
    <Form.Item name="username" rules={[{ required: true, message: 'Please enter your username!' }]}>
      <Input placeholder="Username"/>       
    </Form.Item>

    <Form.Item name="password" rules={[{ required: true, message: 'Please enter your password!' }]}>
      <Input.Password placeholder="Password"/>       
    </Form.Item>

    <Button type="primary" style={{width:200,borderColor:'gray',background:'gray'}} htmlType="submit">Login</Button>
  </Form>
</div>
)
}
export default App;

You Have to define Routes as mentioned below if you want Redirect to work

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import Root from './root'

ReactDOM.render(
  <Root />,
  document.getElementById('root')
);

Root.js:

import React from 'react'
import {Route, BrowserRouter, Switch} from 'react-router-dom'
import LoginComponent from './component/LoginComponent'; 
import WelcomeComponent from './component/WelcomeComponent';
import NotFoundPage from './NotFoundPage'

export default = () => {
    return (
      <BrowserRouter>
       <Switch>
        <Route exact={true} path={'/Welcome'} component={WelcomeComponent}/>
        <Route exact={true} path={'/Login'} component={LoginComponent}/>
        <Route component={NotFoundPage} />
       <Switch>
      <BrowserRouter/>
    )
}

After this your Redirect should work you can also use { usehistory } as mentioned in the first answer

Also, check this Programmatically navigate using react router using different versions but first, you have to implement Routes as mentioned above.

You can more information on https://reactrouter.com/web/guides/quick-start

2
  • I was able to accomplish redirection by defining a Root component as you have mentioned, but only by using history API as the answer above. The Redirect component still does not work.Any idea on that? I need to use Redirect since I feel its more cleaner. Also, which is considered the best practice for redirection?
    – CuteBoy
    Commented Aug 30, 2020 at 14:15
  • whats happening in your code is basically that funtion is returning a react object but its not rendering if you want this to work use if(isLooged) return <Redirect to='/Welcome' /> outside the "onFinish" function before your return Commented Sep 1, 2020 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.