ziondork
ziondork

Reputation: 169

Return exists but it still says, "Nothing was returned from render."

First of all, I have try searching and reading similar questions. I have even found something very similar to my problem. But none helped.

So, I have this projected route component but its giving me this error.

import React from 'react';
import { Route, useHistory } from 'react-router-dom';
import Cookies from 'js-cookie';

const ProtectedRoute = ({ component: Component, ...rest }) => {
    const token = Cookies.get('token');
    const history = useHistory();

    const renderComp = (props) => {
        if (token) {
            return <Component {...props} />;
        } else {
            return history.push('/');
        }
    };

    return <Route {...rest} render={renderComp} />;
};

export default ProtectedRoute;

And here is the component I am rendering through protected route,

import React from 'react';

export default function Greet() {
    return (
        <div>
            <h1>Hello</h1>
        </div>
    );
}

Please help, and explain why its happening. As far as I understand, I am returning something from the method. Then what?

Upvotes: 3

Views: 127

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

Update your renderComp function to be like this:

const renderComp = (props) => {
    if (token) {
        return <Component {...props} />;
    } else {
        history.push('/');
        return null;
    }
};

A React component should return some jsx or null. So basically, instead of returning history.push('/'); you need to return null. Because history.push('/'); returns undefined, hence if you return history.push('/'); you are returning undefined.

Upvotes: 1

Related Questions