Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Dom Redirect needs to refresh the page to work

I am using react-router-dom and I experience a weird behavior when redirecting. I'm trying to redirect from / to /something. So I used:

        <Switch>
            <Redirect
                exact
                from='/'
                to='/something'
            />
            <Route
                component={Garden}
                exact
                path='/something'
            />
        </Switch>

When I open localhost:3000/ I get redirected to localhost:3000/something but the page is blank. When I refresh the page or access /something directly, the page is displayed as expected.

A similar behavior happens when I use react-router-hash-link to handle anchor tags. When setting the scrolling to smooth scroll, I can see the page smoothly scrolling but as soon as it reaches the tag, the page becomes blank. For it to work, I need to refresh the page which is quite inconvenient.

thank you,

like image 854
Dojabato Avatar asked Jan 18 '26 06:01

Dojabato


1 Answers

The code block that you have shown in the question looks good.

You might be configuring the router incorrectly.

See working demo here I created here which uses your switch code. Check the router configuration and apply it to your code base.

Router

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

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Router>
        <Nav />
        <Switch>
          <Redirect exact from="/" to="/something" />
          <Route component={Home} exact path="/something" />
        </Switch>
      </Router>
    </div>
  );
}

component

const Home = props => {
  const [val, setVal] = useState();
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(res => res.map(user => user.username))
      .then(userNames => setVal(userNames));
  });
  return <div>Home - {val}</div>;
};

export default Home;
like image 134
gdh Avatar answered Jan 19 '26 20:01

gdh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!