Aessandro
Aessandro

Reputation: 5771

Add active class on Link in react

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

Answers (2)

Mayank Shukla
Mayank Shukla

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

Darokan
Darokan

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

Related Questions