Home > Net >  toggle only one li element on react
toggle only one li element on react

Time:11-02

i would like to switch the colors between the active element on my project, but this way both of them are changing the style on click, how could i fix this? thanks!

function Language() {
  
  const [style, setStyle] = useState(false);
  
  const changeStyle = () => {   
    setStyle(!style);
  };

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

CodePudding user response:

Instead of using a boolean as a state, you can try to use the index of the active element as the state:

function Language() { 
  const [active, setActive] = useState(-1); // -1 represents no active element
 
  const changeStyle = (index) => {   
    setStyle(index);
  };

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

Then you'll be able to check if the index of this li is the same as the active index.

CodePudding user response:

You can set the code of the active li as the state value and check if the state value is equal to the code value of the li or any other unique value.

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>
    </>
  );
}
  • Related