I'm trying to transform some of my class-component to functional-component. but my "toogle" active class not working with hooks, please what am I doing wrong, this is my script.
import React from "react";
import "./styles.css";
export default class ActiveState extends React.Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 0
};
}
handleOnClick = index => {
this.setState({ activeIndex: index });
};
render() {
const boxs = [0, 1, 2, 3];
const box = boxs.map((el, index) => {
return (
<button
key={index}
onClick={this.handleOnClick.bind(this, index, this.props)}
className = {this.state.activeIndex === index ? "active" : "unactive"}
>
{el}
</button>
);
});
return <div className="App">{box}</div>;
}
}
and this is what i tried using hooks , but not working :
import React, { useState } from "react";
import "./styles.css";
export default function ActiveHooks() {
const [activeIndex, setActiveIndex] = useState(0);
const handleOnClick = index => {
setActiveIndex({ index });
};
const boxs = [0, 1, 2, 3];
const box = boxs.map((el, index) => {
return (
<button key={index} onClick={handleOnClick} className= {activeIndex === index ? "active" : "unactive"}>
{el}
</button>
);
});
return <div className="App">{box}</div>;
}
thanks in advance.
Try this:
function App() {
const [activeIndex, setActiveIndex] = React.useState(0);
const handleOnClick = index => {
setActiveIndex(index); // remove the curly braces
};
const boxs = [0, 1, 2, 3];
const box = boxs.map((el, index) => {
return (
<button
key={index}
onClick={() => handleOnClick(index)} // pass the index
className={activeIndex === index ? "active" : "unactive"}
>
{el}
</button>
);
});
return <div className="App">{box}</div>;
}
ReactDOM.render( <App /> , document.getElementById('root'))
.active {
background-color: green
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With