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

What is the best way to send put and delete requests through a form using node.js and express.js?

Attempting to send a put request: Put form code snippet: <form id="for" action="/people" method="post"> <div class=""> <input type="text" name="Name" value=<%= data[0].name %> > </div> ...

Limiting the combinations of types in TypeScript

I have a dilemma: type TypeLetter = "TypeA" | "TypeB" type TypeNumber = "Type1" | "Type2" I am trying to restrict the combinations of values from these types. Only "TypeA" and "Type1" can be paired together, and only "TypeB" and "Type2" can be paired tog ...

Unable to assign a value to a dropdown using Angular.js and PHP

I am encountering a slight issue with setting the data as a selected value in a dropdown after fetching it from the database. Below is an explanation of my code. plan.html: <div class="input-group bmargindiv1 col-md-12"> <span class="input-g ...

Add a hyperlink to a div element without directly editing the HTML code

Is it possible to add a link to the div using JavaScript instead of changing the HTML and inserting an <a>-tag? <div class="some-class">Some content</div> ...

What are the best practices for avoiding text wrapping around a DIV?

I have scoured this site extensively, searching for a solution to my problem. What I thought was a simple issue has left me frustrated after hours of trying to figure it out on my own. So, I've finally admitted defeat and turned to seek help... Here& ...

Ensure all columns have the same height as the shortest column

While many solutions exist on Stack Overflow for making columns equal height based on the largest content, I am specifically interested in making all columns equal height based on the smallest column. https://i.sstatic.net/Xlcyh.png In this scenario, my ...

Learn how to create a half and half color scheme in an HTML table

I have created an HTML table that resembles a calendar. Various events are registered in the calendar, each distinguished by its color. However, I am looking to change the colors of the cells to be half and half. The image I desire is similar to this: C ...

Using Conditions in a Javascript For Loop

I would like to utilize a for loop to achieve the following task. Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options. If the ...

Tips for transforming a menu into a dropdown menu

Is there a way to convert the current menu into a Dropdown menu? Currently, the menu is not collapsing and it keeps opening. Any suggestions on how to achieve this? Here is an example for reference: https://i.stack.imgur.com/2X8jT.png ar ...

JavaScript fails to display image slideshows upon loading

Currently, I am utilizing a slideshow feature in order to display any additional images that may be retrieved from the globalgiving api. However, there is an issue with the slideshow not appearing when the page is initially loaded or when opening a modal, ...

What methods and applications are available for utilizing the AbortController feature within Next.js?

My search application provides real-time suggestions as users type in the search box. I utilize 'fetch' to retrieve these suggestions from an API with each character input by the user. However, there is a challenge when users quickly complete the ...

Adding a Vue component to HTML using a script tag: A step-by-step guide

Scenario: I am working on creating a community platform where users can share comments. Whenever a comment contains a URL, I want to turn it into a clickable component. Challenge Statement: I have a dataset in the form of a string and my aim is to replac ...

Developing dynamic 3D cubes

In my latest project, I am attempting to construct a unique structure composed of 3D cubes arranged in a stacked formation. Each of the individual cubes within this structure is designed to be interactive for users. When a user hovers over a cube, it trigg ...

Utilizing unique layouts for specific views in sails.js and angular.js

I am currently working on a Sails.js + Angular.js project with a single layout. However, I have come across different HTML files that have a completely different layout compared to the one I am using. The layout file I am currently using is the default la ...

Is it possible to implement an automatic clicking function on a bootstrap navigation bar similar to a carousel?

I am working on a website with a bootstrap navigation bar similar to the one shown in this image : bootstrap nav <ul class="nav nav-tabs" id="tab_home" role="tablist"> <li class="nav-item" role="pres ...

The SunEditor onChange event does not reflect updated state information

software version next: 12.0.7 suneditor: 2.41.3 suneditor-react: 3.3.1 const SunEditor = dynamic(() => import("suneditor-react"), { ssr: false, }); import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS Fi ...

Is it considered poor practice to modify a Bootstrap class in Bootstrap 4?

For instance: form-control appears like this Would it be considered inappropriate if I incorporate this scss code? .form-control { -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ea ...

Are elements in React Native PanResponder capable of being clicked?

While I have movable panresponders, I also require the ability to click on one for an onPress event. Is it achievable? At present, they are <View> elements. If I attempt to switch them to <TouchableOpacity> or a similar element, it results in ...

Challenges with Vue and the <noscript> element

I recently deployed a vue app and everything seems to be functioning as expected. However, I encountered an issue when trying to view the page source in any browser - the actual content is not visible and instead, the body section starts with a message ins ...

Applying styled text to a Node.js chat application

I developed a chat application using node.js which allows users to enter a username and send messages. The messages are displayed in a <ul> format showing "username: message". I was looking for a way to make the username appear bold and in blue color ...