Home > OS >  In React, how do I render a stateless component that is passed in as a prop?
In React, how do I render a stateless component that is passed in as a prop?

Time:01-02

I want to render a component based on whetehr a user is logged in

              <PrivateRoute
                    authed={isAuthenticated} path="/unapproved-list/"
                    component={UnapprovedList}
              />

The PrivateRoute component is set up like so

import React, { Component }  from 'react';
import { Redirect } from 'react-router';
import { Route } from 'react-router-dom';

const PrivateRoute = ({component, authed, ...rest}) => {
  console.log("in private route, authed: "   authed);
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}

export default PrivateRoute;

However, when authentication is true, this line

Component {...props} />

is resulting in the below error

TypeError: instance.render is not a function
finishClassComponent
node_modules/react-dom/cjs/react-dom.development.js:17160
  17157 | } else {
  17158 |   {
  17159 |     setIsRendering(true);
> 17160 |     nextChildren = instance.render();
        | ^
  17161 | 
  17162 |     if ( workInProgress.mode & StrictMode) {
  17163 |       instance.render();

Not sure how to structure my private route to properly render the component. I would prefer not to change the component structure, which is currently like the below

const UnapprovedList = () => {
    const [unapprovedCoops, setUnapprovedCoops] = React.useState([]);   ...
    return (
        <>
            {loadErrors && (
              <strong className="form__error-message">
                {JSON.stringify(loadErrors)}
              </strong>
            )}

            {loadingCoopData && <strong>Loading unapproved coops...</strong>}

            <RenderCoopList link={"/approve-coop/"} searchResults={unapprovedCoops}  columnOneText={"Unapproved Entities"} columnTwoText={"Review"} />
        </>
    )
}

export default UnapprovedList;

CodePudding user response:

The <Component {...props} /> line refers to the Component class imported from the React instead of the component prop because of the first letter upper vs lower case.

Try the following:

const PrivateRoute = ({ component: WrappedComponent, authed, ...rest }) => {
  console.log("in private route, authed: "   authed);
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <WrappedComponent {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}
  • Related