Reputation: 5771
I have the following:
class Link extends React.Component {
render () {
return (
<li data-id={this.props.el}>{this.props.el}</li>
);
}
}
class Nav extends React.Component {
render () {
var links = ['name', 'color', 'design', 'share'],
newLinks = [],
that = this;
links.forEach(function(el){
newLinks.push(<Link activeClass={that.props.active} key={el} el={el} />);
});
return (
<ul>
{newLinks}
</ul>
);
}
}
the value of this.props.active could be " 'name', 'color', 'design', 'share' " same as the array.
Based on that value I would like to assign an active class to the matching li with same data-id={this.props.el} value..
Upvotes: 0
Views: 327
Reputation: 104539
I think this is what you want to achieve:
class Link extends React.Component {
render () {
return (
<li className={this.props.activeClass} data-id={this.props.el}>{this.props.el}</li>
);
}
}
class Nav extends React.Component {
render () {
var links = ['name', 'color', 'design', 'share'],
newLinks = [],
that = this;
links.forEach((el, i)=>{
newLinks.push(<Link activeClass={that.props.active == el ? 'active': ''} key={i} el={el} />);
});
return (
<ul>
{newLinks}
</ul>
);
}
}
Upvotes: 1
Reputation: 26
class Link extends React.Component {
render () {
var liClass = this.props.isActive ? 'active' : '';
return (
<li className={liClass} data-id={this.props.el}>{this.props.el}</li>
);
}
}
class Nav extends React.Component {
render () {
var links = ['name', 'color', 'design', 'share'],
newLinks = [],
that = this;
links.forEach(function(el){
newLinks.push(<Link isActive={el === that.props.active} key={el} el={el} />);
});
return (
<ul>
{newLinks}
</ul>
);
}
}
Upvotes: 1