How Mapping Routes in React Router with Protected Function?

Viewed 5657

I Try To Handling my code with React Route in map and protected function;

This The array for components;

import LoginContainers from "../Containers/LoginContainers/LoginContainers";
import RegisterContainers from "../Containers/RegisterContainers/RegisterContainers";
import ChattingApp from "../Containers/ChattingApp/ChattingApp";

const RoutesMaster = [
    {
        Path: '/login',
        Component: LoginContainers,
        Title: 'Login',
        AuthRequired: false
    },{
        Path: '/register',
        Component: RegisterContainers,
        Title: 'Register',
        AuthRequired: true
    },{
        Path: '/',
        Component: ChattingApp,
        Title: 'Janus Chat',
        AuthRequired: true
    },
]

And this the code in main component;

import React from 'react';
import {BrowserRouter, Switch, Route, useHistory} from "react-router-dom";
import RoutesMaster from "./RoutesMaster";

const RoutesRender = (Routes, Key) => {
    const History = useHistory();

    if (Routes.AuthRequired) {
        History.push("/auth/login");
    } else {
        return (
            <Route exact key={Key} path={Routes.Path} render={(props) => <Routes.Component {...props} />} />
        )
    }
}

const RoutesProvider = () => {
    return (
    <React.Fragment>
        <BrowserRouter>
            <Switch>
                {RoutesMaster.map((Routes, Index) => (
                    <RoutesRender Routes={Routes} Key={Index} />
                ))}
            </Switch>
        </BrowserRouter>
    </React.Fragment>
);
}

export default RoutesProvider;

But it's show this message; "Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of Router.Consumer."

1 Answers

You are returning undefined, or rather returning nothing in method RoutesRender, and react requires you to return in VDOM at least null.

Here is your code with change and comment to see where it is:

const RoutesRender = ({ Routes, Key}) => {
  const History = useHistory();

  if (Routes.AuthRequired) {
    History.push('/auth/login');
    return null; // This is return value that is needed
  } else {
    return <Route exact key={Key} path={Routes.Path} render={(props) => <Routes.Component {...props} />} />;
  }
};
Related