0

Im making a private route in my react app that only routes the user if they're authenticated. I keep getting this error,

Uncaught Error: [PrivateRoute] is not a component. All component children of must be a or <React.Fragment>

So, I know this has to do with v5 and v6 react. here is the code I have so far.


import React from 'react';
import { Route, Routes, Navigate } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom';
import { Consumer } from './Context';

export default function PrivateRoute ({ component: Component, ...rest }){
    return (
        //This wraps the component with the requirement that a request must come with authentication
        <Consumer>
            {context => (
                <BrowserRouter>
                    <Routes>
                        <Route
                            {...rest}
                            render={props => context.authenticatedUser ? (
                                <Component {...props} />
                            ) : (
                                <Navigate to={{
                                    pathname: '/signin',
                                    state: { from: props.location }
                                }} />
                            )
                            }
                        />
                    </Routes>
                </BrowserRouter>
            )}
        </Consumer>
    );
};

Not really sure what I'm doing. But I got this far. I'm not sure if I even need to wrap this function in a . I did wrap it in a because I was told that I can do that with React v6 but that still didn't fix the problem. any pointers would be much appreciated.

I tried updating some of the code from react v5 to v6 but with no success. I think its something to do with props but I'm not sure.

I really wasn't expecting much to happen, so far I'm only getting that single error mentioned above thankfully.

kol
  • 19
  • 1

0 Answers0