Wednesday, 31 May 2017

How do you render a Component in a React-Router Route?

So I'm trying to make an authorization function that hits my node server and returns a simple boolean, which will determine which component will be rendered for a specific Route.

render((
    <Router>
        <div>
            <Route exact path="/" render={ async _ => {
                const auth = await isLoggedIn();
                console.log(auth);
                if (auth) {
                    return <Index />;
                } else {
                    return <Login />;
                }
            }} />
            <Route path="/create" component={Create} />
            <Route path='/login' component={Login} />
        </div>
    </Router>
), document.getElementById('root'));

Now, the async callback is working fine, it's logging false, but I keep getting this error in my console:

Uncaught Error: Route.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

How do I conditionally return a Component in a route render function? (Note that onEnter is replaced in react-router v4, so I can't use that hook).



via Sterling Archer

No comments:

Post a Comment