ページのURLを取得する
props.history.location.pathname;
Reactのhistoryにはページ遷移の履歴が入っている
上記のようにReactRouterのpropsからhistoryを取ってくることができる。
startsWith / includesWith
ある文字列が含まれている時はtrueを返す。
①const pagePath = this.props.history.location.pathname;
②const isActive = pagePath.startsWith(***)
①今いるページのURLをpagePathに渡す。
②pagePathに***が含まれていればtrueを返す
タブアイコンの色が変わるようにする
index.js
class FooterTabItem extends React.Component {
render() {
const pagePath = this.props.history.location.pathname;
const isActive = pagePath.startsWith(this.props.link)
//今いるページのURLにthis.pros.link(Footer.jsの変数linkで定義されてるもの)
//が含まれているか?
const Icon = this.props.icon
//Footer.jsのiconから取得
return (
<Link to={this.props.link}>
<Icon className={isActive ? styles.activeTab : styles.tab} />
//isActiveがtrueだったらstyles.activeTab、falseだったらstyles.tabになる
//→style.module.scssの記載している色になる
</Link>
)
}
}
export default withRouter(FooterTabItem);
Footer.js
import FooterTabItem from './index'
<FooterTabItem icon={なんかのアイコン} link={routes.home()} />
style.module.scss
.activeTab {
color: red;
}
.tab {
color: green;
}