Reputation: 22668
I am learning React JavaScript library. I want to create a simple web-app with the following layout: menu + submenu + content. I use react 15.0.2, react-router 2.4.0, babel 6.5.2 and webpack 1.13.0.
I am able to create menu + content layout but I do not know what is the best practice to add a sub-menu section.
My app looks like this:
Home ~ About ~ Contact ~ Profile
content...
I want to add a sub-menu under the Profile menu item, but the first 3 menu items do not have sub-menu. So if I click on the About and Contact link then I want to see the proper content under the main menu bar. If I click on the Profile link then a submenu needs to be shown. Click on the submenu items the content needs to be displayed under the menu+submenu pairs:
Home ~ About ~ Contact ~ Profile
Profile-Submenu 1 ~ Profile-Submenu 2 ~ ...
content...
App.js
ReactDom.render(
<Router>
<Route component={MainLayout}>
<Route path="/" component={Home} />
<Route path="home" component={Home} />
<Route path="about" component={About} />
<Route path="contact" component={Contact} />
<Route path="profile" component={Profile} />
</Route>
</Router>,
document.getElementById('root')
);
MainLajout.js
export default class MainLayout extends React.Component {
render() {
return (
<div>
<MainMenu />
<main>{this.props.children}</main>
</div>
);
}
}
MainMenu.js
export default class MainMenu extends React.Component {
render() {
return (
<div style={style.container}>
<Link to='/'>Home</Link>
{'\u00a0'}~{'\u00a0'}
<Link to='/about'>About</Link>
{'\u00a0'}~{'\u00a0'}
<Link to='/contact'>Contact</Link>
{'\u00a0'}~{'\u00a0'}
<Link to='/profile'>Profile</Link>
</div>
);
}
}
Could you please guide me to the right direction?
Upvotes: 3
Views: 15138
Reputation: 10219
You could probably pass the current path as a prop to MainMenu
export default class MainLayout extends React.Component {
render() {
return (
<div>
<MainMenu path={this.props.location.pathname} />
<main>{this.props.children}</main>
</div>
);
}
}
Then in your main menu
export default class MainMenu extends React.Component {
render() {
let submenu = null;
if (/^\/profile/.test(this.props.path)) {
submenu = <div style={style.submenu}>
<Link to='/profile/submenu-1'>Submenu 1</Link>
<Link to='/profile/submenu-2'>Submenu 2</Link>
</div>
}
return (<div>
<div style={style.container}>
<Link to='/'>Home</Link>
{'\u00a0'}~{'\u00a0'}
<Link to='/about'>About</Link>
{'\u00a0'}~{'\u00a0'}
<Link to='/contact'>Contact</Link>
{'\u00a0'}~{'\u00a0'}
<Link to='/profile'>Profile</Link>
</div>
{submenu}
</div>);
}
}
Upvotes: 5