Utilizing React JS: Displaying or Concealing Specific Components Based on the URL Path

Is there a way to dynamically change the navbar items based on the URL without having separate navbar components for each side? My current navbar design features 3 links on the left side and 3 links on the right, but I want to display only one side at a time.

For example, when visiting pages like /page-1, /page-2, or /page-3, I would like to show only the links on the left side. Conversely, when on pages such as /page-4, /page-5, or /page-6, I want to display the links on the right side. I've attempted to use match.params for this purpose without success. How can I achieve this functionality? Apologies for any language barriers in my request.

Layout.js

...

export default class Layout extends Component {
  render() {
    return (
      <div>
        <Route path="/:name" component={Navbar} />
        <SomeContentComponent />
      </div>
    );
  }
}

Navbar.js

const Navbar = ({ match }) => {

  const currentPage = match.params.name

  return (
    <div>
      <ul className="left">
        <li><Link to="/page-1">Page 1</Link></li>
        <li><Link to="/page-2">Page 2</Link></li>
        <li><Link to="/page-3">Page 3</Link></li>
      </ul>
      <ul className="right">
        <li><Link to="/page-4">Page 4</Link></li>
        <li><Link to="/page-5">Page 5</Link></li>
        <li><Link to="/page-6">Page 6</Link></li>
      </ul>
    </div>
  )
}

Answer №1

If you need to conditionally display either the left or right div, you can achieve it using the following code snippet:

const Navbar = ({ match }) => {

  const { url } = match;
  const showLeft = ['/page-1', '/page-2', '/page-3'].indexOf(url) > -1;

  return (
    <div>
      {showLeft && (<ul className="left">
        <li><Link to="/page-1">Page 1</Link></li>
        <li><Link to="/page-2">Page 2</Link></li>
        <li><Link to="/page-3">Page 3</Link></li>
      </ul>
      )}
      {!showLeft && (
      <ul className="right">
        <li><Link to="/page-4">Page 4</Link></li>
        <li><Link to="/page-5">Page 5</Link></li>
        <li><Link to="/page-6">Page 6</Link></li>
      </ul>
      )}
    </div>
  )
}

Answer №2

The main functionality of the <Route /> component is to dynamically render specific sections of a webpage based on the defined route.

Starting from version 3, React router suggests treating <Route /> as a regular component rather than following a declarative route structure. For more information, refer to: https://reacttraining.com/react-router/web/guides/philosophy

Following this approach, you can implement the following:

Navbar.js

import LeftNav from "./LeftNav.js";
import RightNav from "./RightNav.js";

const Navbar = () => (
  <>
    <Route path={['/page-1', '/page-2', '/page-3']} component={LeftNav} />
    <Route path={['/page-4', '/page-5', '/page-6']} component={RightNav} />
  </>
)

In your left and right components:

LeftNav.js :

export default () => (
  <ul className="left">
    <li><Link to="/page-1">Page 1</Link></li>
    <li><Link to="/page-2">Page 2</Link></li>
    <li><Link to="/page-3">Page 3</Link></li>
  </ul>
)

RightNav.js :

export default () => (
  <ul className="right">
    <li><Link to="/page-4">Page 4</Link></li>
    <li><Link to="/page-5">Page 5</Link></li>
    <li><Link to="/page-6">Page 6</Link></li>
  </ul>
)

To understand how to utilize multiple paths with the <Route /> component, visit: Multiple path names for a same component in React 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

Create a connection between a div and a React component, allowing for the seamless transfer of

I'm looking to implement a feature where clicking on a specific div will redirect the user to another page, similar to React Router. However, I currently lack the knowledge to make it happen. Below is the code snippet in question: const Card: React.FC ...

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

Whenever I try to execute watir-webdriver, I notice that the CSS file is

Currently, I am in the process of learning how to utilize watir-webdriver in ruby for my QA tasks. However, a recurring issue arises when running my watir-webdriver scripts on certain sites - some pages have missing CSS Files. This particular problem seems ...

What is the mechanism behind YouTube automatically playing music videos when we visit a channel's homepage?

Since Chrome version 66, autoplay of videos with music has been restricted to muted playback. However, I recently noticed that on certain YouTube channel pages, the videos were autoplaying with sound, even when using the HTML video API. How is YouTube able ...

What is the proper way to manage the refresh token on the client's end within a JWT system?

Curious about what exactly occurs on the client side when the refresh token expires. Is the user directed to a login page and remains logged in, or does the client side log them out automatically? My understanding is that the refresh token is saved in an ...

Error encountered when attempting to reference multiple Select MenuItems in Material UI

Recently, I've been encountering a perplexing error when attempting to open a multiple Select in React+Next.js using Material UI: Error: Argument appears to not be a ReactComponent. Keys: retry This issue seems to be related to a ref. It occurs with ...

Troubleshooting problem with Z-Index conflict in Flash animation

I am facing an issue with two HTML divs - one containing a flash movie and the other simple text. I want to place the textual div on top of the flash movie div, but no matter how I set their positions in CSS or adjust their Z-Index values, the text keeps ...

What is causing the IE CSS fix to fail in Internet Explorer 8? The IE statement does not seem to end properly

Greetings! I recently attempted to implement an IE fix on my website, however, it seems that it is not effective for IE8. Should I provide more specific instructions? <!--[if IE]> <link rel="stylesheet" type="text/css" href="/AEBP_Homepage_12 ...

Is it necessary to download and install plotly if I am using the cdn in my HTML file?

I'm currently developing an online application using Flask. The user input is collected with d3.js and sent to app.py, where it is used for an API call to retrieve the necessary data. This data is then returned in JSON format to JavaScript for renderi ...

Modify a unique element within an array stored in the state using Redux toolkit

I'm currently attempting to modify a property of an object within an array stored in my state. export const changeStatus = createAsyncThunk('changeStatus', async (arg) => { const todo = arg const response = await axios.put(`${URL} ...

Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute: <p class="form-row form-row-wide" data-child-field="child_has_jacket"> </p> Even after trying with jQuery : jQuery( ...

React - Having trouble loading content on initial load - could be a state management problem

For some reason, the data on my page only loads when I refresh it. I suspect that the issue lies in state management, but I can't seem to figure out how to fix it. Any assistance would be greatly appreciated! After a user signs up for an account and ...

Using preventDefault in the compositionend event does not make any difference

var inputNode = document.getElementById('view_1'); inputNode.addEventListener('compositionend', function(e) { console.log(e.cancelable); // true e.preventDefault(); }); <div id="view_1" class="view" contenteditable="true> &l ...

When using the `Node fs.readstream()` function, the output includes `<Buffer 3c 3f 78 6d 6c ...>`, which is not in a readable

Handling a large XML file (~1.5gb) in Node Js by streaming it to process data in chunks has proven challenging due to the complexity of the documentation. A simple code snippet I am currently using is: var fs = require('fs'); var stream = fs.c ...

Sketch the borders of the element (animated)

Seeking a way to create a button with an animated border that looks like it is being drawn. Current progress involves some code, but it's not working smoothly with border-radius set. (keep an eye on the corners) https://codepen.io/anon/pen/MbWagQ & ...

Is it possible to manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

issue with horizontal scrolling in react menu component

**Hi there, I'm encountering an issue with react-horizontal-scrolling-menu. When scrolling, it moves to the right excessively and causes other elements to disappear. Additionally, adding overflowX: 'scroll' to the BOX doesn't activate t ...

Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular. The code snippet I've written looks like this: $q.all({ a: $q.then(func1, failHandler), b: $q.then(func2, failHandler), c: $q.then(func3, failHandler), }).then(func4); Is it guaranteed ...

Button with small width containing an icon and text

I am trying to create a simple HTML button that has an icon on top and a description below it. <div class="mybtn"> <div><img src="someimage.png"></div> <div>Button description</div> </div> My question is, ...

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...