preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.01k stars 156 forks source link

How to do a conditional redirect? #467

Closed ashep closed 2 months ago

ashep commented 2 months ago

Hi there. I need to redirect from one route to another conditionally.

App:

export default class App extends React.Component {
    render(): JSX.Element {
        return (
            <Router>
                <Home path={"/"} needSetup={true} />
                <Settings path={"/settings"}/>
            </Router>
        );
    }
}

Home:

export default class Home extends React.Component {
    componentWillMount() {
        if (this.props.needSetup) {
            console.log("redirecting...");
            route("/settings", true);
        }
    }

    render(): JSX.Element {
        return (
            <React.Fragment/>
        );
    }
}

I see the "redirecting..." output in the console, but no redirect is happening.

Thank you.

rschristian commented 2 months ago

Looks like a bug, though I'd recommend switching to preact-iso. preact-router unfortunately hasn't been maintained.

ashep commented 2 months ago

Thank you @rschristian!