0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ページのURLごとにタブアイコンの色を変える(React)

Posted at

ページのURLを取得する

props.history.location.pathname;

:point_up_tone1: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;
} 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?