How to utilize the ternary operator efficiently to evaluate multiple conditions in React

Is there a way to change the style based on the route using react router? I want the description route to display in orange when the user is in the description route, white when in the teacher-add-course route, and green for all other routes. However, the last condition is not rendering properly when on other routes. I have tried setting these conditions with the ternary operator but it's not working as expected. Can anyone provide assistance?

I attempted to use the ternary operator for the conditions and it worked correctly for the teachers-add-course and description routes. However, when navigating to other routes like requirements, the condition does not apply as intended.

import React from 'react';
import { FaBookOpen } from 'react-icons/fa';
import { Link, useLocation } from 'react-router-dom';
import '../../asset/css/Teachers-overview/TeachersDashboardSidebar.css'

const TeachersDashboardSidebar = () => {
    let location = useLocation()
    console.log(location.pathname);
    return (
        <div className='sidebar-container'>
            <div className='sidebar-content-wrapper'>
                <div className='overview-wrapper'>
                    <div className='d-flex flex-column align-items-center'>
                            <div className= {`${location.pathname=== '/teacher-add-course'? 'progress-book-icon bg-orange':'progress-book-icon bg-complete'}`}>
                                <FaBookOpen className="text-white " />
                            </div>
                        <div className={`${location.pathname==='/teacher-add-course'? 'candle-basic':'candle-success'}`}></div>
                    </div>
                    <Link to="/teacher-add-course"><span className="text-semilight font-weight-bold mt-2 ml-3">Overview</span></Link>
                </div>
                <div className='bold d-flex'>
                    <div className='d-flex flex-column align-items-center'>
                            <div className={`${location.pathname=== '/teacher-add-course/description'?'bg-orange':'teacher-add-course'?'progress-book-icon':'bg-complete'} `}>
                                <FaBookOpen className="text-white " />
                            </div>
                        <div className={`${location.pathname==='/teacher-add-course/description'? 'candle-basic':'candle-success'}`}></div>
                    </div>
                    <Link to="/teacher-add-course/description"><span className="text-semilight font-weight-bold mt-2 ml-3">Description</span></Link>
                </div>
                <div className='text-warning bold d-flex'>
                    <div className='d-flex flex-column align-items-center'>
                            <div className={`${location.pathname=== '/teacher-add-course/requirements'? 'progress-book-icon bg-orange': '/teacher-add-course/gallery'? 'progress-book-icon bg-complete':'progress-book-icon'}`}>
                                <FaBookOpen className="text-white " />
                            </div>
                        <div className={`${location.pathname==='/teacher-add-course/requirements'? 'candle-basic':'candle-success'}`}></div>
                    </div>
                    <Link to="/teacher-add-course/requirements"><span className="text-semilight font-weight-bold mt-2 ml-3">Requirements</span></Link>
                </div>
            </div>
        </div>
    );
};

export default TeachersDashboardSidebar;

Answer №1

Make sure to include the full comparison for each option in the conditional statement.

<div className={`${location.pathname === '/teacher-add-course/requirements'? 'progress-book-icon bg-orange': location.pathname === '/teacher-add-course/gallery'? 'progress-book-icon bg-complete':'progress-book-icon'}`}>

Remember, you can simplify the code by directly assigning the result of the conditional operator to the className without using a template literal.

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

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Having trouble getting the onClick action to work on the pivot item

I need to render different components based on a flag value, and the components must be rendered outside of the pivotitem tag. class DisplayComponent extends Component<any, any> { constructor(props: any) { super(props); this.s ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...

Spring MVC is preventing the completion of the request due to CORS restrictions

Currently facing a CORS problem while trying to send requests from React.js to my spring MVC application. I have attempted to enable it in the ApplicationContext.xml file with no success. Added the following lines to the applicationcontext.xml file, but e ...

Does Three.js lighting adjust according to the bundler used?

Today, I decided to streamline my portfolio project by transitioning it from standard HTML to the Vite bundler for easier dependency management. I simply copied and pasted the existing code, making adjustments to the imports since I had been using relative ...

Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's perm ...

I am facing an issue where my Javascript hide and show function is not working properly when clicked. Despite not giving

I am currently working on a Javascript onClick function to toggle the visibility of content in a lengthy table. I initially set part of the table's class to display: "none" and added a button to show the hidden content when clicked. However, nothing i ...

JavaScript - Issue encountered while reaching the bottom of the webpage

While conducting tests using Firebug/Firefox, I am trying to execute a simple command that will scroll the page to the bottom. Here is the command: window.scrollBy(0,3000); Seems straightforward, right? When testing on certain websites like Yahoo.com ...

Tips for choosing a nested element within a div using CSS

I'm looking to target a specific child element within a div using CSS. Here's the HTML code I have: <div class='body'> <text>This is a text element</text> </div> Instead of adding a class or an ID, I want to ...

Steps for deactivating a button based on the list's size

I am trying to implement a feature where the user can select only one tag. Once the user has added a tag to the list, I want the button to be disabled. My approach was to disable the button if the length of the list is greater than 0, but it doesn't s ...

Take out property that was placed in the "style" tag

One particular static HTML file that I have consists of the following code: <style> p { overflow-wrap: break-word; word-break: break-word; hyphens: auto; } </style> <div id="wrapper"> <p>Insert text here ...

Is there a way to access and parse a CSV file from a URL within a Next.js project?

Currently working on a Next.js application available here. The task at hand requires reading a CSV file from a specific URL within the same repository in multiple instances. Unfortunately, I am encountering difficulties retrieving this data. You can locate ...

When props are passed through the root element, the data becomes inaccessible

I am currently using React in conjunction with an EJS template. I am attempting to pass data from an API to React, but I am facing difficulties in finding a way to accomplish this. Here is the API code snippet: module.exports.home_get = async (req,res) =&g ...

Disable the "top" property for the Material UI Drawer component

I'm currently working on implementing a Persist Left Drawer from Material UI that slides in from the left side. However, I don't want the drawer to cover the entire left side of the page. Essentially, I want to remove the "top" style property men ...

Dealing with CSS overflow issues in Safari, Chrome, and the ancient IE 6

Are Safari and Chrome compatible with overflow? How does IE 6 or higher handle overflow? ...

Change wiki text into HTML using Python for showcasing on a webpage

Despite trying various tools for 6 hours, I have been unable to find one that can properly interpret wikitext like the example below: '<center>Welcome to the world's foremost open content<br><big><big><big>'&ap ...

Node application experiencing issues retrieving SVG files during production

When testing my application locally, the svg files display correctly with the code below (Angular.js variables are used within curly brackets): <img ng-src="img/servant_{{servant.personality}}.svg" draggable="false"> However, once deployed on Herok ...

Tips for identifying a scroll down gesture on a touch device with jQuery

I have a method for infinite scroll that is triggered like this: $(window).on('scroll resize load', function() { // execute the infinite scroll method }); It is triggered by these events: scroll resize load However, it does not seem to ...

How can I stop the space bar from activating its default action unless I am inside an input field

If we want to stop the default scrolling behavior when pressing the space bar on the document, we can use the following code snippet: $(document).keypress(function(event) { event.preventDefault(); }); However, this approach won't work if there ar ...

What is the best way to resize an image to fit its surroundings within a nested box?

Have you ever heard of a website called SPAM? It has a unique homepage that I want to replicate using JavaScript, jQuery, and some CSS. My main challenge is figuring out how to adjust the image size to match the center box on the page. I want to create th ...