When using React Router, make sure to set the navigation tab's style class to "active" if you are

I'm currently working on a React and react-router application that uses 2 nested routes to create a total of 3 routes: /, /about, /contact. When I click on the Links to navigate to each route, the tab on my navigation bar - which is located in the parent route - changes its style to show it's active using some Bootstrap magic. However, the issue arises when I visit /about or /contact, as the nav tab does not remain active. Since I am new to React, I assume that I need to bind the style attribute to a condition that checks the property of the route, props, or state of the component. Nevertheless, I'm uncertain about how to go about doing this and would greatly appreciate any help.

Here is the simplified layout where the nav is:


export default class Layout extends React.Component {
  render() { 
      return (
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li><Link to="/about">About</Link></li>
            <li><Link to="/contact">Contact</Link></li>
          </ul>
        </div>
    )}}

In the < li > part, I believe I need something like class={if this.props.children == About, class=active, class=""}

The code for rendering the routes:


render((
  <Router history={hashHistory}>
    <Route path="/" component={Layout}>
      <Route path="/about" component={About}/>
      <Route path="/contact" component={Contact}/>
    </Route>
  </Router>
  ), document.getElementById('app'))

Therefore, as mentioned above, the li element needs to check if the Layout's props.children are null, or if they are equal to About or Contact. I'm really unsure about how to compare the value of this.props.children if it's a React component.

Any assistance provided in advance will be highly appreciated!

Answer №1

Our previous discussion in the comments shed light on how to retrieve the active class name for your <li> elements:

Please note: Assuming you are utilizing React Router v1.0.x, it is highly recommended to upgrade to the latest version - 2.0, refer to the Upgrade Guides

import { Link, History } from 'react-router'

const Tab = React.createClass({
  mixins: [ History ],
  render() {
    let isActive = this.history.isActive(this.props.to, this.props.query)
    let className = isActive ? 'active' : ''
    return <li className={className}><Link {...this.props}/></li>
  }
})

// Usage similar to <Link/>, resulting in an anchor within an `li` tag
// with an automatic `active` class added.
<Tab href="foo">Foo</Tab>

If you prefer ES6 classes, the approach remains quite similar, replacing mixins by retrieving history from the context (learn more here - for React Router v1.0.x branch).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React and Express are two powerful technologies that work seamlessly

Here lies the contents of the mighty index.html file <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <s ...

A guide on harnessing the power of getServerSideProps

I'm a beginner in Next.js and I've just started learning about pre-rendering. I'm a bit confused on how to update props data from getServerSideProps. _app.tsx import type { AppProps } from 'next/app'; function MyApp({ Component, ...

Having trouble loading CSS in Firefox?

After creating a basic responsive website, I encountered an issue where Mozilla was not loading the CSS properly when the site was hosted on my server. Interestingly, the CSS loaded fine on Chrome and IE when viewed from my computer. Here is a snippet of ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

Is it possible to change the ajax src attribute without initiating a new request?

My goal is to create an iframe using a system that utilizes HTTP authentication. Below is the code I am currently working with: <iframe id="dashboard"></iframe> <script type="text/javascript"> $.ajax( ...

Resolved issue with background image display on Mac Chrome

I'm currently in the process of developing a website that incorporates fixed background images for smooth transitions between sections. The implementation is entirely CSS-based and has been effective in all browsers except for one: Chrome on Mac (Vers ...

A SyntaxError was encountered because functions in strict mode code must be declared either at the top level or directly within another function

Hey there, I'm encountering a strange issue with my project. Everything runs smoothly when I run it in Developer mode using `grunt server`. However, when I try to run it in production mode with `grunt build`, I encounter an error: Uncaught SyntaxEr ...

Extracting information from the fileuploadfield in Ext JS 3

Currently utilizing Ext.ux.FileUploadField within Ext JS 3.3.1. Aiming to retrieve the file data from the form without having to submit it. Wondering if anyone has insight on whether this is feasible. Currently able to view the filename but not the actual ...

Tips for resolving issues with adjusting row height when using expandable rows in a react virtualized list

I've recently encountered a challenge with expandable panels (Material-UI) within rows in a react virtualized list. The problem lies in the auto-adjusting heights of the panels, and despite researching similar issues on Stack Overflow and the react-vi ...

implementing a sidebar menu using AngularJS

I am currently working with bootstrap and AngularJS to create a sidebar menu. Here is the code I have for it: <ul class="nav navbar-nav"> <li><a href="#"><span class="glyphicon glyphicon-send"></span> Link</a& ...

Tips for modifying a particular element within a class?

I am seeking guidance on how to modify a specific class attribute in CSS/JS/JQuery when hovering over a different element. Here is an example: <h1 class="result">Lorium</h1> <h1 class="result">Ipsum</h1> <h1 class="result">Do ...

When clicking on a div with the CSS property user-select set to none, the selected text in a contenteditable element is

I'm currently working on a unique JavaScript rich text editor that utilizes div elements with the CSS property user-select: none instead of traditional buttons. While this approach works perfectly in Firefox, I've encountered a major issue with G ...

Why isn't my ajax call working after using window.close?

Whenever I click the button on my page, a small window opens and the value from the window is sent to my controller before closing. However, I noticed that when I include the window.close() line, the controller does not get hit. It works perfectly fine wit ...

Regular Expression - Locate all numerical values within text formatted with HTML

I am attempting to locate all the numbers within an HTML document. However, I want to ensure that I exclude numbers that are part of a word, such as "o365", "high5", and similar instances. Here is my current approach, but it does not successfully avoid w ...

Issue with the styling of the fourth level menu option persists

I'm stuck trying to style the fourth level and can't figure out why. Would really appreciate some help untangling this CSS mess! Check out the Fiddler: Menu Demo ...

How come (23 == true) is incorrect but (!!23 == true) is correct? After all, there is === for exact comparisons

The question boils down to this: are both 23 and true truthy values? If so, shouldn't they be equal under the loose comparison operator ==? However, there is also the strict comparison operator === for cases where precise equality is required. UPDATE ...

Flipping json stringify safety

In my NextJS React application, I encountered an issue with circular references when using getInitialProps to fetch data. Due to the serialization method used by NextJS involving JSON.stringify, it resulted in throwing an error related to circular structur ...

Several directories for viewing in Node.js with Express

I have been researching different solutions, but I am still unsure about how to effectively integrate Express with multiple view folders. Imagine an Express application divided into distinct parts, each organized in its own subfolder: app +partA + ...

What is the most efficient way to modify the variables for numerous images within a JavaScript canvas?

I'm a newcomer to using Javascript in a canvas, and coding with javascript overall. My primary goal is the following: Create numerous fireballs (images) that spawn randomly with each having a fixed y-value and random x-value. The fireballs should t ...

Updates made to the Transform property in Mui Theme are not appearing in the browser

I'm looking to modify the MuiInputLabel.outlined. While I can see various changes when inspecting in the browser, I'm having trouble seeing the transform property change specifically. This is the current configuration of my MuiInputLabel: MuiInp ...