Creating an active tab using Material UI on a particular route

I've encountered an issue with Material UI tabs and need help figuring out how to resolve it. I have a navbar with three different tabs that link to separate URLs, but two of them are quite similar. Take a look at my code snippet below:

<Tabs indicatorColor="primary" value={this.state.tabsValue} onChange={this.setTabsValue}>
                    <Tab className={classes.tab}
                      label="Main"
                      value="main"
                      component={Link}
                      to="/main"
                      classes={{ selected: classes.selectedTab, }} />
                    <Tab className={classes.tab}
                      label="Shoes"
                      value="shoes"
                      component={Link}
                      to="/sale/shoes"
                      classes={{ selected: classes.selectedTab, }} />
                    <Tab className={classes.tab}
                      label="Sale"
                      value="sale"
                      component={Link}
                      to="/sale"
                      classes={{ selected: classes.selectedTab }} />
                  </Tabs>

Below is the function setTabsValue that manages change events:

  setTabsValue = (obj, val) => {
    this.setState({
      tabsValue: val
    });
  };

Additionally, the setTabsValue function is triggered when there is a change in props:

  componentWillReceiveProps(nextProps) {
    const newRoute = window.location.pathname.split('/')[2];
    if (this.state.tabsValue !== newRoute) {
      // update currentRoute for user ping
      this.currentRoute = newRoute;
      this.setState({
        tabsValue: this.isMainRoute(newRoute)
      });
    }

The issue arises from the similarity in the last two tab routes containing the word 'sale'. This causes the active tab underline to appear under the 'Sale' tab even when navigating to 'Shoes', creating unexpected behavior.

When on the 'Sale' tab and switching to 'Shoes', after a prop update, the active tab reverts back to 'Sale', which is not intended.

If anyone has insights on this issue, your assistance would be greatly appreciated. Thank you!

Answer №1

If you're looking for a convenient solution, React Router is highly recommended and it's my go-to choice for navigating through different pages in my projects. Check out React Router here

Take a look at this example below which demonstrates how you can create an application that effectively directs you to specific components for each page.

const App = () => {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/topics">Topics</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/topics">
            <Topics />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

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

Is there a way to dynamically adjust the background box size to fit the inner boxes using node.js?

click here for the screenshot of the webpage I'm working on Hey there! I'm currently working on a school project for my assignment. I'm having some trouble adjusting the size of the background grey box to fit with the content inside, such a ...

Can I assign a custom form id before manually triggering submission using AJAX?

I have developed an interesting code snippet that uses AJAX to submit a form only if the form has an ID attached to it. $(document).delegate('form', 'submit', function(event) { var $form = $(this); var id = $form.attr('id& ...

What is the CSS solution for eliminating a line break immediately following the first word?

While designing an email template in html/css for a mailing list, I encountered an issue where on mobile devices the line breaks after the first word for every paragraph. You can see an example of this problem here. The code for the email template was gen ...

Retrieving JSON information from a PHP file and saving it as a global variable

Currently, I am in the process of developing a cordova mobile application and my goal is to extract all the data from a PHP page that outputs JSON data. This information will then be stored in a global variable for easy local access. Here is an example of ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...

Looking at a 3D wireframe cube using three.js

I am a new three.js user and still learning Javascript. I successfully completed the "Getting Started" project on threejs.org, which consisted of a rotating cube, with no issues. However, when I attempted to add a wireframe to the project, it suddenly stop ...

Assigning objects in Vue.js methods

I am working on a Vue component where I need to select a specific value from an array of objects and then copy certain fields from that value into Vue data. <div class="container"> <h4>Add Item</h4> <form @submit.prevent="ad ...

Creating clones of <li> elements using JQuery and appending them to the end of a <ul> list

I have a regular ul li list and I am looking to add an additional li based on the first one in the list. Here is the HTML: <div id="gallery"> <ul> <li>Point Nr 1<p>lol</p></li> <li>Point Nr 2</li> <li> ...

When the height is set to 100vh, the Div and Image appear misaligned vertically

Could someone explain why there is a vertical separation between the div and the image? <div style="height: 100vh; display: inline-block;width: 50%; background-color: blue">TEST </div><!-- --><img src="photos/openening.jpg" alt="SICK ...

Is it possible to import a component from a production build of create-react-app?

Has anyone tried importing a component from a production build of create-react-app? Situation: I have one CRA project that has been built for production. Inside this project, there is a component named ExampleButton. Now, I am working on a second CRA pro ...

`Inconsistencies in state management across components`

Creating a calendar with the ability to add notes for each day is my main goal. The structure of my components is organized as follows: App component serves as the common component that renders the main Build component. The Build component utilizes CellBui ...

Sending template reference from one Angular component to another

I have a main grid component that includes smaller grid-item components. The majority of these grid items navigate to a specific route when clicked. However, there is one particular item that should open a modal window instead of navigating. Is there a wa ...

Attempting to understand the concept of "this" in my JavaScript code. One aspect is functioning correctly while the other is not

Currently, I am improving my knowledge of JavaScript by reworking certain jQuery examples from a reference book. In this particular snippet of code, I am implementing a click listener for a tab to change to an active state once the user clicks on it. va ...

NodeJS MySQL failing to retrieve the most updated data post-write

I'm struggling to solve an issue where after performing data operations (create, update, delete) and then querying for the data afterwards, I receive the previous version of the data rather than the updated version. For example: Let's say I hav ...

Issue with utilizing addEventListener("load") in Firefox in conjunction with <iframe>

I've encountered an issue with my iframe when it is used as the target for a form. In all major browsers, except for Firefox, the iframe successfully removes the main element upon pressing the submit button. However, in Firefox, the main element is re ...

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...

What could be causing my JavaScript source to fail to load in an HTML document?

Currently, I am in the process of creating a basic offline dinosaur game using HTML, JS, and CSS that is well-known to everyone. I have been diligently working on it and have successfully made everything function for a few hours. However, out of nowhere, m ...

Implementing a node.js application deployment with pm2 to ensure zero downtime

While there are countless tutorials on developing chat applications using socket.io and node.js, the event-driven advantage of Node is undeniable for building chat apps. However, a recent thought crossed my mind - how can I ensure the sustainability of my ...

The functionality of the Wordpress editor is impaired when the parent element is set to display:none during rendering

My goal is to create a popup window with text fields and a wp_editor. The content is already rendered in the footer but only set to display none. I have made attempts at implementing this, however, they are not working perfectly. Each approach has its own ...