0

For example, how would I redirect http://localhost:3000/ automatically to http://localhost:3000/dashboard on load, with out any auth controllers or any sort of logic. Just a plain redirect from when I run "npm run start".

import React from "react"; import { BrowserRouter as Router, Route, Switch, Redirect, } from "react-router-dom";

import history from "./history";

import DashboardScreen from "./components/screens/DashboardScreen";

class App extends React.Component {
  render() {
    return (
      <Router history={history}>
        <Switch>
          <Route exact path='/'>
            <Redirect to='/dashboard' component={DashboardScreen} />
          </Route>
          <Route exact path='/passwords' component={DashboardScreen} />
          <Route exact path='/notes' component={DashboardScreen} />
          <Route exact path='/addresses' component={DashboardScreen} />
        </Switch>
      </Router>
    );
  }
}

export default App;
1

3 Answers 3

2

You can use react-router-dom for routing, you can following my code for example:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <Router>
      <App />
    </Router>
  </StrictMode>,
  rootElement
);

App.js

import { Switch, Route, Redirect } from "react-router-dom";
import "./styles.css";

export default function App() {
  return (
    <Switch>
      <Route exact path="/">
        <Redirect to="/dashboard" />
      </Route>
      <Route exact path="/dashboard">
        <div>
          <h1>This is Dashboard</h1>
        </div>
      </Route>
    </Switch>
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

How would I redirect with a component? I updated the post for context
the redirect is only to redirect the path of your router. so if you need render component on path "/dasboard", you can create <Route path="/dashboard" component={DashboardScreen} />
youre correct, it worked
0

If you are using react router you can try something like this


 <Route exact path="/" render={() => <Redirect to="/dashboard " />} 

Comments

0

You could try something like this with the help of plain js and react only

const Redirect = ({to}) => window.location = to;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.