Saturday, March 9, 2019

ReactJS > Load Different Component Based on Different Conditions

I want to load different component based on URL or as I think, any different condition. So if URL is myreact.com/user/1000 it should load AdminUserComponent and if URL is myreact.com/user/5000 it should load StaffUserComponent. Its just an example, we can handle any type of conditions based on situation.
So our Route would be like

<Route path="/user/:user_param" component={UserDecideWrapper} />
And the UserDecideWrapper is nothing but a if else condition block to decide which component will load or not.

class ComponentDecide extends MainActivity {
    render() {
        let id = parseFloat(this.props.match.params.id);
        if (isNaN(id)) {
            return <Home {...this.props}/>
        }
        if (id === 1000) {
            return <AdminUserComponent {...this.props}/>
        }
        return <StaffUserComponent {...this.props}/>
    }
}
{...this.props} indicated that props will be passed as constructor.

No comments:

Post a Comment