What is the best way to include or exclude a class in a React functional component?

I've been working with React TypeScript, and I'm encountering some issues with adding or removing an active class when clicking on list items. The code seems to be unreliable at times, so I'm looking to enhance it for better functionality. Can anyone assist me in improving the following function code?

Below is the function that requires updating:

   const menuItems = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function handleActiveLink(e: any) {
        menuItems.forEach((item) => item.classList.remove('active'))
        e.classList.add('active')
    }
    menuItems.forEach(item => item.addEventListener('click', (e) => handleActiveLink(item)))

Full Code with HTML:


export default function MobileNavigation() {
    const menuItems = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function handleActiveLink(this: any) {
        menuItems.forEach((item) => item.classList.remove('active'))
        this.classList.add('active')
    }
    menuItems.forEach(item => item.addEventListener('click', handleActiveLink))

    return <div className='mobile-navigation'>
        <ul>
            ...
        </ul>
    </div>;
}

Answer №1

Your current code is written in pure VanillaJS, not using Typescript or React. I recommend exploring both Typescript and React by reading up on them, creating example projects, and experimenting with their functionalities. Here is a helpful resource to get you started: https://medium.com/codex/typescript-and-create-react-app-11bdebcbf763

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 it better to have JavaScript and HTML in separate files or combined into a single HTML file?

Do you notice any difference when coding in both HTML and JavaScript within a single .html file compared to separating HTML code in a .html file and JavaScript code in a .js file? Does the functionality remain the same in both scenarios? For example, in t ...

java ArrayList

It's been a while since I worked with Java last, and I'm looking to refresh my memory on a few things. import java.util.*; public class bitStrings { public static void main(String [] args){ Scanner inputBitString = new Scanner(Syst ...

Custom directives are unable to interact with inbuilt directives

var app = angular.module("myDiscuss", []); app.controller("TabController", function() { this.tab = 0; this.subTab = 0; this.like = 0; this.selectLike = function(setTab) { this.like= setTab; }; this.selectTab = function(setTab) { this. ...

Prevent the div from moving beyond the boundaries of its container while anim

After experimenting with a javascript image panner that I put together from various code snippets, I have decided to switch to a simpler approach. However, I need some guidance on a few things. Below is the code for the left and right buttons: <div id ...

`store and showcase images taken from file input`

On my website, I have integrated a feature that allows users to capture images from their available cameras. While the web version places the video capture onto a canvas, for mobile devices, I am utilizing an input button to facilitate image capture. This ...

Updating React state from another component - using useState

How can I efficiently update this state in React so that it changes when a specific button is clicked within the <FirstPage /> component? I'm struggling with finding the best approach to accomplish this. Any suggestions? const SignUp = () => ...

Types that depend on function input parameters

I am facing a challenge with a function: function navigateOptions(currentScreenRoute: 'addGroup' | 'addGroupOnboarding', group: GroupEngagement) { const navigationKey = currentScreenRoute === 'addGroup' ? 'addGroupPeopl ...

Removing Specific Items from a List in React: A Step-by-Step Guide

I have developed a basic ToDo List App. The functionality to display tasks from the input form is working correctly, but I am facing issues with deleting tasks when the Delete button is clicked. export class TaskList extends Component { constructor(pr ...

Prevent Sending Blank Forms with Stripe js

Currently, I am working on a solution to prevent users from submitting the stripe form when certain inputs are left empty. To achieve this, I have integrated stripe.js elements into my form and implemented the form submission handling within my vue compone ...

Automated updating feature with jQuery

Is there a way to use jQuery code to automatically refresh a page after navigating back in the browser history? Here is an example of what I have tried: jQuery(".form_" + form_count).html("<div id='message'></div>") jQuery('#me ...

Regular expression for the validation of emails using a delimiter

Can someone help me create a regex expression for emails? This is what I have so far: \S+@\S+\.\S+ I want to repeat this X times with a ; separator. Any ideas on how to achieve this? For example, the pattern should allow strings like: ...

JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays? The structure of my array is as follows: tabs=[ {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: ...

The API GET request is not returning any data, even though Postman is able to retrieve the

While attempting to make an API call to a remote server, I encountered the following error initially: No 'Access-Control-Allow-Origin' header is present on the requested resource. To temporarily resolve this issue, I appended the https://cors- ...

Ways to Determine if the Content in the CKEditor has Been Altered

Is there a way to detect changes in the content of CKEditor? I want to trigger a JavaScript function every time the content is updated. ...

An assertion error is thrown in Node JS due to a missing path requirement

I have a basic node.js application implemented: var mongo = require('./helpers/mongo_utils.js'); var express = require('express'); var user = require('./models/users.js'); mongo.connect(function (err) { if (err) throw er ...

Direct your cursor to move across the sphere surface in THREE.JS

I'm working on a project to develop an interactive globe where users can drag points on the surface using their mouse cursor. Here is the code snippet I've been working on Currently, I've managed to set up the main sphere and a smaller red ...

Ways to restrict the display or height of a select HTML element

Is there a way to minimize the display or height of a select tag? Here is an image of the desired outcome: I am open to using Javascript, jQuery, CSS, or simply converting it to a list format. I just need guidance on how to achieve this or a sample to re ...

Bot activities involve keeping information updated

I implemented a feature in the status to display the number of online members out of the total, but it doesn't update in real-time unless the bot is restarted. Is there a way to have this information automatically update with new data when the activit ...

I'm looking to determine the value of a checkBox that has been marked using vueJS. How can

Currently, I am in the final stages of a project involving Laravel and VueJS. However, I have encountered a problem. In one modal, I am able to select a checkbox (there may be multiple or none), and I need to retain the value of the selected checkbox when ...

Creating a Vue.js project with Viddler's top-notch video player for seamless playback and dynamic

Hey there fellow developers! I just dove into learning Vue.js yesterday, and I'm already hooked! I'm currently working on a small application that utilizes Vue (1.0.28) to showcase an online course. You can find a JSFiddle link at the end of thi ...