Reputation: 465
I am trying to dynamically style a React element: In the nav bar, I would like to make the font color of the <div>
displaying the current page to be different from the other <div>
s representing other pages. I have passed into my <NavBar>
component's props the params representing the current page.
From this information, I have figured out a way to achieve what I am trying to do: I store the <div>
s representing the page links in an object and wrap the selected page in another <div>
carrying a 'selected'class name.
However, I could envision scenarios where this solution would disrupt styling in place since it adds a wrapper element and classes within the wrapper element would take precedence over the 'selected' class.
Does anyone know a better way? I have posted my solution and the context below:
export default class NavBar extends React.Component {
constructor(props) {
super(props);
}
render() {
const pages = {
my_subscribed_docs:
<div className='nav__row2-item'>Documents I'm Subscribed To</div>,
my_created_docs:
<div className='nav__row2-item'>Documents I've Created</div>,
new_doc:
<div className='nav__row2-item'>
<div className="plus-icon">+</div>
<div className='nav__row2-text_left-of-icon'>New Document</div>
</div>,
};
const currentPage = this.props.path.slice(1);
pages[currentPage] =
<div className='nav__row2-item--selected'>{pages[currentPage]}</div>;
debugger;
return (
<nav>
<div className="nav__row1">
<div className="nav__logo">Worksheet Generator</div>
<div style={{cursor: 'pointer'}} onClick={this.props.logout}>
Logout
</div>
</div>
<div className="nav__row2" >
{ Object.values(pages).map( page => (
<div key={shortid.generate()}>{page}</div>)
) }
</div>
</nav>
);
}
}
Upvotes: 0
Views: 76
Reputation: 1726
If you want to dynamically add a class
to your component, I recommend using classnames library. This is pretty much the way to do it when using external stylesheets.
Upvotes: 0