Reputation: 3770
So here's my issue. I'm using HOC inside my React Router. So it looks like that:
<BrowserRouter>
<div className="main__container">
<Route exact path="/" component={authHOC(MainView)} />
<Route path="/article" component={authHOC(Article)} />
<Route path="/apps" component={authHOC(AppList)} />
</div>
</BrowserRouter>
Now, I'd like to pass some props to my wrapped components. I'd like to have something like this:
component={authHOC(Article({ header: true })}
so to pass props to my component. Above won't work. Is there a way to pass it?
My HOC component looks like this:
export default function(ProtectedComponent, addProps) {
return class LoginPage extends Component {
checkUserAuth = async() => {
const token = await api.getAuthToken();
this.setState({ isUserLoggedIn: !!token, loading: false });
};
redirectToAuth = () => <Redirect to="/login" />;
render() {
const { isUserLoggedIn, loading } = this.state;
if(!loading) {
return isUserLoggedIn ? (
<ProtectedComponent {...this.props} {...addProps} />
) : this.redirectToAuth();
}
return null;
}
};
}
Upvotes: 2
Views: 2314
Reputation: 223104
Components shouldn't be called directly like Article({ header: true })
, unless this is done on purpose.
A higher-order component can accept a component and additional arguments that are used in wrapped component, as shown in the guide, e.g.:
<Route exact path="/" component={authHOC(MainView, { header: true })} />
and
const authHOC = (Comp, props) => <Comp {...props}/>;
In case authHOC
is third-party HOC that cannot be modified, it should be provided with enhanced component:
<Route exact path="/" component={
authHOC(props => <MainView {...props} header={true} />)
} />
Upvotes: 3