skip to Main Content

I am fairly new to react, I’m building a website and I want to keep a page private if my user does not have sufficient scope to access it. I have the following code:

Update: I tried just setting setCanAccess(true) and still got the error. When I comment that line out entirely, there’s no error. I also tried setting it outside of the .then() callback and still got the error.

function ProtectedPage(props, children) {
    var [canAccess, setCanAccess] = useState(false);

    useEffect(() => {
        LoginManager.getStoredUser().then(user => {
            setCanAccess(user.scopes.includes(props.scope));
        });
    }, [props.scope]);

    return (
        <>
            {canAccess ? (
                <>{children}</>
            ) : (
                <>
                    <Spacer height="150px" />
                    <p>
                        You need to be logged in with the proper permissions to
                        view this page. Here is the scope: {props.scope}.
                    </p>
                    <Link to="/login">Log In</Link>
                </>
            )}
        </>
    );
}

and

function Secret() {
    return (
        <ProtectedPage scope="owner">
            <PageHeader>Secret Page</PageHeader>
        </ProtectedPage>
    );
}

I keep getting the following error:Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead. Any help is appreciated, I’ve been trying to figure this out for hours and nothing makes sense anymore lol.

Thanks 🙂

2

Answers


  1. You are rendering {children} which is itself an object and when we render an object directly it always gives us that error.

    Login or Signup to reply.
  2. Well you should read the docs. Component props have children in them, so you should access children as props.children and remove the second parameter from the ProtectedPage component.

    function ProtectedPage(props) {...}
    
    <>{props.children}</>
    

    This should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search