question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

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?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:5
  • Comments:22 (5 by maintainers)

github_iconTop GitHub Comments

6reactions
ErBahugunacommented, Apr 16, 2018

Use NavLink to specify active classname without any extra work. like this import { NavLink } from ‘react-router-dom’

<NavLink className="nav-link" activeClassName="active" to='/about'>About</NavLink>

5reactions
awesomejerrycommented, Jun 5, 2016

With Redux, I’m currently using this hack:

server.js

app.get('*', async (req, res, next) => {
    ...
    store.dispatch(setRuntimeVariable({
      name: 'currentPathname',
      value: req.path,
    }));
    ...
});

client.js

  const removeHistoryListener = history.listen(location => {
      if (currentLocation !== null) {    // to prevent first-time calling
          store.dispatch(setRuntimeVariable({
            name: 'currentPathname',
            value: location.pathname,
          }));
      }

    ....
  });

MyComponent.js

....
export default connect(state => ({
  pathname: state.runtime.currentPathname,
}))(withStyles(s)(MyComponent));

just sharing, hoping to find a more robust and redux-free method.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I add an active class to a Link from React Router?
First import it import { NavLink } from 'react-router-dom'; · Use an activeClassName to get the active class property. · Style your class...
Read more >
Add an active className to the link using React Router
The first method is to use the react-router-dom inbuilt method of NavLink instead of Link. The NavLink supports activeClassName which can help ...
Read more >
Active NavLink Classes with React Router - Ultimate Courses
Thankfully adding an active class in React Router v6 proves nice and simple once we dive in. Our <NavLink> component provides an isActive ......
Read more >
How to Add Active Class in Map Items in React Js - positronX.io
Step 1: Install React Project ; Step 2: Add Bootstrap Module ; Step 3: Create Component File ; Step 4: On Clicked Add...
Read more >
How To Add Active Class To Current Element - W3Schools
Learn how to add an active class to the current element with JavaScript. Highlight the active/current (pressed) button: 1 2 3 4 5....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found