I can't toggle a particular button. I want to toggle that particular button in an array of buttons. Here is demo code link. Please correct it and share solved problem.
import { useState } from 'react';
import { data } from './data';
import "./styles.css";
export default function App() {
const [state, setState] = useState({
toggle: true,
index: ''
})
const onJoin = () => {
setState({
...state,
toggle: !state.toggle
})
}
const onRequest = () => {
setState({
...state,
toggle: !state.toggle
})
}
return (
<div className="App">
{data.map(data => {
return(<div className='container'>
<h1>{data.name}</h1>
{state.toggle ?
<button onClick={() => onJoin()}>Join</button>
:
<button onClick={() => onRequest()} >Request</button>
}
</div>)
})}
</div>
);
}
You are using one state variable for all buttons. You need an array to keep track of which buttons are toggled
Instead of making toggle a boolean, make it a boolean array.
import { useState } from "react";
import { data } from "./data";
import "./styles.css";
export default function App() {
const [state, setState] = useState({
toggle: [],
index: ""
});
const onJoin = (index) => {
setState((state) => ({
...state,
toggle: state.toggle.filter((t) => t !== index)
}));
};
const onRequest = (index) => {
setState((state) => ({
...state,
toggle: [...state.toggle, index]
}));
};
return (
<div className="App">
{data.map((d, index) => (
<div key={index} className="container">
<h1>{d.name}</h1>
{state.toggle.includes(index) ? (
<button onClick={() => onJoin(index)}>Join</button>
) : (
<button onClick={() => onRequest(index)}>Request</button>
)}
</div>
))}
</div>
);
}