I have tried:
element: <ProtectedRoute component={ProjectBoard} prop1={prop1} prop2={prop2}/>
I get the error Type '({ prop1, prop2 }: Props) => JSX.Element' is not assignable to type 'ComponentType<{}>'.
element: <ProtectedRoute component={<ProjectBoard prop1={prop1} prop2={prop2}></ProjectBoard>}/>
And then I get the error Type 'Element' is not assignable to type 'ComponentType<{}>'.
///// ProtectedRoute.tsx
interface ProtectedRouteProps {
component: ComponentType;
}
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
component,
...args
}) => {
// HOC from Auth0, the component I want to pass props to is passed here
const Component = withAuthenticationRequired(component, {
onRedirecting: () => (
<div></div>
),
})
return <Component {...args}></Component>;
}
///// app,tsx
const myComponenet = (age: number) => {
return <p>{age}</p>
}
// I want to pass in the props though my router here
const router = createBrowserRouter([
{
path: '/myComponent',
element: <ProtectedRoute component={myComponenet} age={someState} />,
}
])
I want to pass props into and have them be passed to myComponent. Or some other way to get state from the current level into any component rendered by
CodePudding user response:
The ProtectedRouteProps
interface is missing the age
prop, but more than this I don't think there's a straight forward way to type variadic props of unknown type and count.
However, I don't see much of a point to this ProtectedRoute
component since it only decorates a component. You should decorate the components first and export the decorated component. From here you can set the routes configuration and pass the props directly to the components that need them.
Example:
MyComponent.tsx
interface MyComponentProps {
age: number;
// and any other props the component consumes
}
const MyComponent = ({ age }: MyComponentProps) => {
return <p>{age}</p>
}
export default withAuthenticationRequired(MyComponent, {
onRedirecting: () => (
<div></div>
),
});
App.tsx
import { createBrowserRouter } from 'react-router-dom';
import MyComponent from '../path/to/MyComponent';
const router = createBrowserRouter([
...
{
path: '/myComponent',
element: <MyComponent age={someState} />, // <-- pass all the props necessary
}
...
]);