0

I would like to redirect to a component in case the data of the success has a certain value. When ajax returns the data, depending on the value of the data redirected to the Contents class that I previously imported. I've been looking for information about the push method My error is: Error: Invariant failed: You should not use <Redirect> outside a <Router>

 import React, { Component } from 'react';
    import { Modal,Button } from 'react-bootstrap';
    import $ from 'jquery'; 
    import {  Redirect } from 'react-router';
    import Contents from './Contents';
    class Login extends Component {
        constructor(props, context) {
            super(props, context);

            this.handleShow = this.handleShow.bind(this);
            this.handleClose = this.handleClose.bind(this);
            this.handleloginClick = this.handleloginClick.bind(this);
            this.handleUsernameChange = this.handleUsernameChange.bind(this);
            this.handlePasswordChange = this.handlePasswordChange.bind(this);

            this.state = {
              show: true,
              username: "",
              password: "",
            };
          }

          handleloginClick(event) {
          var parametros = {
            username: this.state.username,
            password: this.state.password
          }
          const { history } = this.props;

          $.ajax({
            data: parametros,
            url: "https://privada.mgsehijos.es/react/login.php",
            type: "POST",
            success: function (data) {
               }
          });   
      }

      handleUsernameChange(event) {
            this.setState({username: event.target.value});
        }

        handlePasswordChange(event) {
          this.setState({password: event.target.value});
      }
        handleClose() {
        this.setState({ show: false });
      }

      handleShow() {
        this.setState({ show: true });
      }

         render() {


    If(Condicion){     
         return (<Redirect to={'./Contents'} />);
       }
 return (
          //Here my modal.
     );
              }
          }
          export default Login;
  • Possible duplicate of [Automatic redirect after login with react-router](https://stackoverflow.com/questions/29594720/automatic-redirect-after-login-with-react-router) – Garrett Motzner Mar 20 '19 at 19:31

1 Answers1

1

you can use Router dom to navigate.

My fiddle: https://jsfiddle.net/leolima/fLnh9z50/1/

const AboutUs = (props) => {
    
  console.log(props.location.state)
  console.log('Hi, you are in About page, redirecting with router dom in 3 seconds')
  
  setTimeout(() => {
  props.history.push('/')}, 3000);
    
  return <h1>Now we're here at the about us page.</h1>;
};

Full Example:

// Select the node we wish to mount our React application to
const MOUNT_NODE = document.querySelector('#app');

// Grab components out of the ReactRouterDOM that we will be using
const { BrowserRouter, Route, Switch, NavLink, Link } = window.ReactRouterDOM;

// PropTypes is used for typechecking
const PropTypes = window.PropTypes;

// Home page component
const Home = () => {
  return <h1>Here we are at the home page.</h1>;
};

// AboutUs page component
const AboutUs = (props) => {
    
  console.log(props.location.state)
    
  return <h1>Now we're here at the about us page.</h1>;
};

// NotFoundPage component
// props.match.url contains the current url route
const NotFoundPage = ({ match }) => {
    const {url} = match;
  
    return (
    <div>
      <h1>Whoops!</h1>
      <p><strong>{url.replace('/','')}</strong> could not be located.</p>
    </div>
    );
};


// Header component is our page title and navigation menu
const Header = () => {
    // This is just needed to set the Home route to active 
  // in jsFiddle based on the URI location. Ignore.
    const checkActive = (match, location) => {
    if(!location) return false;
    const {pathname} = location;
    
    return pathname.indexOf('/tophergates') !== -1 || pathname.indexOf('/_display/') !== -1;
  }
  
  return (
    <header>
      <h1>Basic React Routing</h1>
      <nav>
        <ul className='navLinks'>
          {/* Your home route path would generally just be '/'' */}
          <li><NavLink to="/tophergates" isActive={checkActive}>Home</NavLink></li>
          <li><Link to={{
            pathname: "/about",
            state: { fromDashboard: true }
          }}>About</Link></li>
        </ul>
      </nav>
    </header>
  );
};


// Out layout component which switches content based on the route
const Layout = ({children}) => {
  return (
    <div>
      <Header />
      <main>{children}</main>
    </div>
  );
};

// Ensure the 'children' prop has a value (required) and the value is an element.
Layout.propTypes = {
  children: PropTypes.element.isRequired,
};

// The top level component is where our routing is taking place.
// We tell the Layout component which component to render based on the current route.
const App = () => {
  return (
    <BrowserRouter>
      <Layout>
        <Switch>
          <Route path='/tophergates' component={Home} />
          <Route path='/_display/' component={Home} />
          <Route exact path='/' component={Home} />
          <Route path='/about' component={AboutUs} />
          <Route path='*' component={NotFoundPage} />
        </Switch>
      </Layout>
    </BrowserRouter>
  );
};

// Render the application
ReactDOM.render(
    <App />, 
  MOUNT_NODE
);
Leonardo Lima
  • 474
  • 5
  • 12