Front end/React
React - navbar item 클릭 후 Link to로 링크 이동시, navbar toggle 되게하기
Ideveloper2
2018. 5. 24. 00:25
React - navbar item 클릭 후 Link to로 링크 이동시, 메뉴 토글되게하기
| 참고 링크
| 시작하기에 앞서,
Link to로 nav bar 링크 이동시, 페이지가 리로드되는게 아니라 메뉴바가 토글(collapse)되지 않고 그대로 남아있는 현상이 발생했었다. 이를 해결하기 위해 위의 링크를 참고하여, 코드를 구현하였다.
참고로 navitem을 Link to 로 구현하는 방법은 아래와같은 속성을 navitem에 주면 되었었다.
componentClass={Link} href="/board" to="/board"
적용시킨 코드
import React, { Component } from 'react';
import classnames from 'classnames/bind';
import { Nav, Navbar, NavItem } from 'react-bootstrap'
import {Link} from 'react-router-dom'
import { compose } from 'recompose';
import { connect } from 'react-redux';
import { LinkContainer } from 'react-router-bootstrap';
import { setMeta } from 'src/redux/meta/actions';
import css from './BootstrapNavbar.scss';
import Const from 'src/consts/const.js'
const cx = classnames.bind(css);
const moduleName = 'BootstrapNavbar';
class BootstrapNavbar extends Component {
constructor(props) {
super(props);
this.state={navExpanded: false};
this.setNavExpanded=this.setNavExpanded.bind(this);
this.closeNav=this.closeNav.bind(this);
}
setNavExpanded(expanded) {
this.setState({ navExpanded: expanded });
}
closeNav() {
this.setState({ navExpanded: false });
}
render(){
const {meta} = this.props;
const {isVisible} = this.state;
return (
<div className={cx(`${moduleName}`)}>
<Navbar className={cx(`${moduleName}-navbar`)}
onToggle={this.setNavExpanded}
expanded={this.state.navExpanded}>
<Navbar.Header className={cx(`${moduleName}-header`)}>
<Navbar.Brand >
<a href="/" className={cx(`${moduleName}-brand`)}></a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse className={cx(`${moduleName}-collapse`)}>
<Nav onSelect={this.closeNav}>
<NavItem aria-haspopup="true" href="tel:01025336009" className={cx(`${moduleName}-collapse-item-tel`)}>
<p>Tel: 010-2533-6009</p>
</NavItem>
<NavItem componentClass={Link} href="/" to="/"className={cx(`${moduleName}-collapse-item`)} >
<img className={cx(`${moduleName}-menuImage`)} src={require('../assets/home.png')}/>Home
</NavItem>
<NavItem componentClass={Link} href="/room" to="/room"className={cx(`${moduleName}-collapse-item`)} >
<img className={cx(`${moduleName}-menuImage`)} src={require('../assets/room.png')}/> 객실
</NavItem>
<NavItem componentClass={Link} href="/surrounding" to="/surrounding" className={cx(`${moduleName}-collapse-item`)} >
<img className={cx(`${moduleName}-menuImage`)} src={require('../assets/trees.png')}/>주변전경
</NavItem>
<NavItem componentClass={Link} href="/board" to="/board" className={cx(`${moduleName}-collapse-item`)} >
<img className={cx(`${moduleName}-menuImage`)} src={require('../assets/pencil.png')}/>게시판
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
);
}
}
export default compose(
connect(
({ meta }) => ({
meta,
}),
{setMeta}
)
)(BootstrapNavbar);