Dynimic child component rendering on same Layout Route

1.9k views Asked by At

I have a Component named Layout that should render different child components depending on the route. Parent component

export default class Layout extends Component{
    render(){
        return (
            <div>
                <div>
                    <div>
                        <Navbar/>
                        {this.props.sidebar}
                        {this.props.content}
                    </div>
                </div>
            </div>
        );
    }
}

In my main.jxs i want to render 3 Route using the Layout component with different ChildComponent passed as sidebar and content props like:

<Route path="/profile" component={sidebar: <Sidebar />, content: <Content />} />
<Route path="/user" component={sidebar: <Sidebar />, content: <User />} />
<Route path="/edit" component={sidebar: <Sidebar />, content: <Edit />} />

Components are imported as well. In other words, i want to dynamically change the content of layout based on the route. How can i achieve this using react-router-dom ?

2

There are 2 answers

0
Arthur On BEST ANSWER

If I got you right you should use render func as prop in Route component (react router 4) In order to can render a several components. See https://reacttraining.com/react-router/web/api/Route/render-func

Also I provide next small example

https://jsfiddle.net/69z2wepo/85086/

2
Ivan Mjartan On

Your approach is correct, but you need define index route that will display layout and your other routes have to be child routes.

I am using this as

 <Route path="/" component={Layout} >
        <IndexRoute components={{ body: LandingPage }} />
        <Redirect from="appdetail/" to="/" />
        <Route path="appdetail/:applicationId" components={{ body: AppDetailPage }} />
 </Route>    

than my Layout looks like:

export class Layout extends React.Component<ILayoutProps, void> {

    /**
     * Renders this object.
     *
     * @return  A JSX.Element.
     */
    public render(): JSX.Element {

        const mainDivStyle: React.CSSProperties = {
            width: "100%",
            height: "100%",
            top: "0px",
            left: "0px",
            backgroundColor: "#f2f2f2",
            fontSize: "12px",
            fontFamily: "Gotham"
        };

        const contentDesktopStyle: React.CSSProperties = {
            height: "100%"
        };


        return (
            <div style={mainDivStyle}>
                    <div id="contentId" style={contentDesktopStyle}>
                        <Header />                        
                        { this.props.body }
                    </div>
            </div>
        );
    }
}