I map through the buttons array and get three buttons. What i want to achieve is to be able to identify which button is clicked and add an active class
import React from "react";
import { useState } from "react";
import style from "./years.module.scss";
const Years = props => {
const [activeClass, setActiveClass] = useState(null);
const buttons = ["year one", "year two", "year three"];
return (
<div className={style.box}>
{buttons.map((button, index) => {
console.log(index,button)
return (
<button key={index} className={`${style.btn} ${style.active}`} >
{button}
</button>
);
})}
</div>
);
};
export default Years;
I use css modules to style the buttons
Just connect handler with each button - if clicked, the state is changed and stores the index
of active button. If it's active - add class.
const changeActiveButton = (i) => () => {
setActiveClass(i);
};
<button
onClick={changeActiveButton (index)}
className={`${style.btn} ${index === activeClass ? style.active : ''}`}
>
<button key={index} className={`${style.btn} ${style.active}`} onClick={()=>setActiveClass(button)} >
{button}
</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.