Skip to content

How can I add a class of active to the Link component? #682

@daiky00

Description

@daiky00

I am trying to do this for Example

<a class="link active">Home</a>
<a class="link">About</a>
<a class="link">Contact</a>
<a class="link">Work</a>
<a class="link">Support</a>

this is how my navigation is

    <div className={cx(s.root, className)} role="navigation">
      <Link className={cx(s.link, 'fa fa-dribbble')} to="/dribbble" />
      <Link className={cx(s.link, 'fa fa-behance')} to="/behance" />
      <Link className={cx(s.link, 'fa fa-linkedin')} to="/linkedin" />
      <Link className={cx(s.link, 'fa fa-twitter')} to="/twitter" />
      <Link className={cx(s.link, 'fa fa-instagram')} to="/instagram" />
      <Link className={cx(s.link, 'fa fa-vimeo')} to="/vimeo" />
    </div>

and this the Link Component code.

import React, { Component, PropTypes } from 'react';
import history from '../../core/history';

function isLeftClickEvent(event) {
  return event.button === 0;
}

function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}

class Link extends Component {

  constructor(props) {
    super(props);
    this.state = {active: false};
  }

  click() {
    this.setState({active: true});
  }

  static propTypes = {
    to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
    onClick: PropTypes.func
  };

  handleClick = (event) => {

    let allowTransition = true;

    if (this.props.onClick) {
      this.props.onClick(event)
    }

    if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
      return;
    }

    if (event.defaultPrevented === true) {
      allowTransition = false;
    }

    event.preventDefault();

    if (allowTransition) {
      if (this.props.to) {
        history.push(this.props.to);
      } else {
        history.push({
          pathname: event.currentTarget.pathname,
          search: event.currentTarget.search
        });
      }
    }
  };

  render() {
    const currentPath = this.to.getCurrentPathname();
    const { to, ...props } = this.props; // eslint-disable-line no-use-before-define
    return <a href={history.createHref(to)} id={this.state.path ? 'active' : null} {...props} onClick={this.handleClick} />;
  }

}

export default Link;

Any Ideas?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions