React class components redirect under conditions

Viewed 45

I'm trying to get React to navigate to the main page when certain conditions are met using the following code.

import './App.scss';
import React from 'react';
import { BrowserRouter, Routes, Route, Link, Navigate } from 'react-router-dom';
import World from './components/World';
import Shop from './components/Shop';
import About from './components/About';

export default class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            query: ''
        };
    }
    render() {
        <BrowserRouter>
           { (window.location.pathname !== '/' ? <Navigate to="/" /> : '') }
           ...
        </BrowserRouter>
    }
}

This works, it does only navigate to '/' when the current location isn't '/', when it gets there it throws the following error which suggests an ifinite loop, the code works fine though (as far as I can tell).

enter image description here

1 Answers

if you are using react-router v6 you can do something like this

    <Route path="*" element={<Navigate  to={"/"}/>} />
Related