How to alternate the display of a single li element in React?

I am looking to swap the colors of the active element in my project. Currently, both elements change style when clicked. How can I resolve this? Thanks!

function Language() {
  
  const [isStyled, setIsStyled] = useState(false);
  
  const toggleStyle = () => {   
    setIsStyled(!isStyled);
  };

  return (
    <>
      <ul className="lang">
        {languages.map(({ code, name, country_code }) => (
          <li key={country_code}>
            <h4 onClick={() => {i18next.changeLanguage(code); toggleStyle()}} className={isStyled ? "cont" : "cont2"}>{name}</h4>
          </li>
        ))}
      </ul>
    </>
  );
}

Answer №1

Consider using the index of the active element instead of a boolean as state in your code:

function Language() { 
  const [active, setActive] = useState(-1); // -1 indicates no active element

  const changeStyle = (index) => {   
    setStyle(index);
  };

  return (
    <>
      <ul className="lang">
        {languages.map(({ code, name, country_code }, i) => ( // use 'i' as index
          <li key={country_code}>
            <h4 onClick={() => {i18next.changeLanguage(code); changeStyle(i)}} className={active === i ? "cont" : "cont2"}>{name}</h4>
          </li>
        ))}
      </ul>
    </>
  );
}

You can then compare if the index of the current li matches the active index.

Answer №2

To determine the state value, you can assign the code of the active list item and compare it with either the code value of the list item or any other unique identifier.

function Language() {
  const [active, setActive] = useState('');      
  const changeStyle = (code) => setActive(code)


  return (
    <>
      <ul className="lang">
        {languages.map(({ code, name, country_code }) => (
          <li key={country_code}>
            <h4 
                onClick={()=>{
                  i18next.changeLanguage(code);
                  changeStyle(code)
                }} 
                className={active===code && "active" }>
                  {name}
            </h4>
          </li>
        ))}
      </ul>
    </>
  );
}

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

Troubleshooting inactive CSS hover animation

Greetings! I'm facing an issue with a CSS hover animation. Here are two demos I've created: In the first DEMO, the animation works perfectly. However, in the second DEMO, it doesn't seem to be functioning. On the second demo, there are two ...

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Adding a certain number of days to a date within an existing ng-module in AngularJS

Hey everyone, I'm new to using AngularJS and I am currently attempting to incorporate one ng-module value into another ng-module date input within AngularJS. For example: if the date is 17-08-2016 and we add 20 days, the expected result should be 03-0 ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

The ƒ character doesn't seem to be a match for the JavaScript regex

I am facing a requirement to only allow (extended) ASCII characters in my input. As a solution, I've implemented a JavaScript regex pattern like this: /^[\x20-\xff]+$/.test("helloê¿£×جáƒ") However, this doesn't work as expect ...

What is the best way to implement transition effects while toggling between light mode and dark in tailwind 2.0?

Currently, I am working on a small project utilizing tailwindCSS and have decided to incorporate a dark mode feature. To achieve this, I created a button that toggles the dark class in the html tag. However, upon testing the functionality, I noticed that t ...

Place a cookie on the alternate language domain

Within my website, we utilize 2 distinct domains, each dedicated to a different language. www.mysite.com en.mysite.com I am interested in implementing JavaScript to establish a cookie on en.mysite.com when clicking a link on www.mysite.com. Here is my ...

Creating a set of labels using values derived from a collection of objects

Looking for advice on how to loop through a Serialized JSON string using an ajax call in JavaScript. I have 8 labels set up and want to assign each key and value from the JSON string to a different label. Any guidance or feedback is appreciated! I'm ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Adjust the CSS for the "a" tag's "title" attribute

I am using jquery.fancybox to create an image modal on my website. I have noticed that I can add a description using the title attribute. However, when the description is too long, the text is displayed on a single line and some of it disappears. How can ...

Utilize JQuery's .load() function to transmit JSON data to your Flask server

I am attempting to utilize JQuery's .load() function in order to transmit data to my Flask server and then, with that information, display a <div> that is loaded into the element making the request. This is what my code snippet looks like: $(&qu ...

The absence of a defined window object is causing issues in the integration of NextJS with

https://i.stack.imgur.com/BNuLw.png My Objective: I wanted to implement a custom title bar using the appWindow functionality from Tauri in order to access methods like appWindow.minimize(), appWindow.toggleMaximize(), and appWindow.close(). The Implementa ...

Issue with scrollIntoView in devices with a width lower than 1200px

In my Angular 5 project, I have a table where each row is generated dynamically using *ngFor and given an id based on the username. <tbody *ngFor="let User of FullTable; let i = index"> <tr id='{{User.username}}'> <th scope="r ...

Encountering an error code of 500 when executing the createIndex function in Pouch

I'm currently working on setting up a basic index, and I have the following code snippet: currentDB.createIndex({ index: { fields: ['name'] } }).then((result) => { }).catch((error) => { }) However, when I try to r ...

Issue with Heroku deployment: SCRIPT5007 error - Property 'apply' is undefined or null. Detected in NodeJs and React application

Encountering a peculiar issue with polyfills, most likely related to Redux in my MERN stack application deployed on Heroku. While I can view the site without any problem in Chrome on my computer, other computers show a blank page with the error message: & ...

Error encountered: AXIOS request failed due to XSRF-TOKEN Mismatch

My server is receiving different X-XSRF-TOKEN headers compared to the cookies being sent when I make requests 2-3 times per second using axios. let axiosInstance = axios.create({ baseUrl: "MY_BASE_URL_HERE", timeout: 20000 } ...

Developing a JSONP functionality

I am currently trying to use JSONP in order to display data within my div. However, the code is not showing anything. I have also included jquery.jsonp.js in my project with the following path: PRJFOLDER->WEBPages->JavaScript->qu ...

how to protect your javascript and php code

I have a question about "injection", specifically javascript injection which I find confusing. Suppose I have a javascript function that sends an AJAX request to get a user's permission level, and then uses an if statement to assign power based on th ...

Having trouble getting an AjaxBeginForm to function properly within a JQuery script on a PartialView

Within the main controller view, we bring in the partial view utilizing the following code: @Html.Partial("MapPartial", Model) Within the Partial View, I aim to display a map. Currently, there is an Ajax beginform with a submit button that ...

Can you explain the purpose of $winstonLoggerConfig<T>() and $winstonLogger<T>() in winston v3?

I'm currently using the winston logger and I want to implement flow typing for it. However, I am unsure of what exactly I should pass to it in order to achieve this. Below is my current logger setup: const logger = createLogger({ ... }); Missing typ ...