Reputation: 1090
I have this app. Everything is workin successfully except what I wrote in this post title.
class PortfolioMenu extends Component {
isActive= (match, location) => {
if (match) {
if (document.querySelector('.portfolio-menu')){
document.querySelector('.portfolio-menu').className += " new-classjs";
}
}
return match;
};
render(){
return (
<div>
<Router>
<div class="wrapper2">
<div class="wrapper-portfolio">
<Route exact path='/portfolio' render={() => <Intro />} />
<Route exact path='/portfolio/casas' render={() => <Casas />} />
</div>
<nav>
<ul className="portfolio-menu">
<li><NavLink activeClassName="active" isActive={this.isActive} exact to="/portfolio">• introdução</NavLink></li>
<li><NavLink activeClassName="active" exact to="/portfolio/casas">• casas</NavLink></li>
</ul>
</nav>
</div>
</Router>
</div>
)
}
}
export default PortfolioMenu
How can you see in the code above, I have this react function that detect if some page is active. This function is working successfully. When I type console.log(page detected)
in its body it shows the result
isActive= (match, location) => {
if (match) {
if (document.querySelector('.portfolio-menu')){
document.querySelector('.portfolio-menu').className += " new-classjs";
}
}
return match;
So the root of the issue is what happen in this function body in this especific case isn't working. I would like to sum the 'new-classjs' besides 'portfolio-menu' class resulting: <ul className="portfolio-menu new-classjs"">
. How can I solve it?
Upvotes: 0
Views: 39
Reputation: 196002
You could keep a state property for the portfolio class and set it accordingly from the isActive
method.
class PortfolioMenu extends Component {
state = {
portfolioClass: ""
};
isActive = (match, location) => {
const { portfolioClass } = this.state;
const newClass = match ? "new-classjs" : "";
if (newClass !== portfolioClass)
this.setState({ portfolioClass: newClass });
return match;
};
render() {
const { portfolioClass } = this.state;
return (
<div>
<Router>
<div class="wrapper2">
<div class="wrapper-portfolio">
<Route exact path="/portfolio" render={() => <Intro />} />
<Route exact path="/portfolio/casas" render={() => <Casas />} />
</div>
<nav>
<ul className={`portfolio-menu ${portfolioClass}`}>
<li><NavLink activeClassName="active" isActive={this.isActive} exact to="/portfolio">• introdução</NavLink></li>
<li><NavLink activeClassName="active" exact to="/portfolio/casas">• casas</NavLink></li>
</ul>
</nav>
</div>
</Router>
</div>
);
}
}
Demo at https://codesandbox.io/s/p91xk60p6j
Upvotes: 2