I have an array of data
const projectTypeValues = [
{ name: 'Hour', value: 'hour'},
{ name: 'Day', value: 'day'},
{ name: 'Session', value: 'session'},
{ name: 'project', value: 'project'}]
From there I am showing the buttons in a material ui buttonGroup through an loop.
{projectTypeValues.map(element=>
<Button variant="contained" color="primary">{element.name}</Button>
)}
how do i implement an onClick function that will make the other buttons in the loop disable except the one that was clicked?
CodePudding user response:
You can manage it by storing a selected button value in state and checking on disabled
time. You can use the button disabled
attribute for disabling. You can store unique
value for matching button disable like name
or id
.
If we use name
for selecting the button so we need to check like this way.
disabled={currentSelect && currentSelect !== element.name}
Example:
const projectTypeValues = [
{ name: "Hour", value: "hour" },
{ name: "Day", value: "day" },
{ name: "Session", value: "session" },
{ name: "project", value: "project" }
];
const App = () => {
const [currentSelect, setSelect] = React.useState(null);
console.log(currentSelect);
return (
<div>
{projectTypeValues.map((element) => (
<div style={{ padding: "10px" }} key={element.name}>
<button
disabled={currentSelect && currentSelect !== element.name}
variant="contained"
color="primary"
onClick={() => setSelect(element.name)}
>
{element.name}
</button>
</div>
))}
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script
crossorigin
src="https://unpkg.com/react@17/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"
></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
import React from "react";
function App() {
const [disable, setDisable] = React.useState(false);
return (
<button variant="contained" color="primary"
disabled={disable} onClick={() =>
setDisable(true)}>
{element.name}
</button>
);
}
CodePudding user response:
You should define a state
for the selected button, something like this:
const [selectedButtonIndex, setSelectedButtonIndex] = useState(-1)
then you need to use map
and get the index and disable
or other buttons:
{projectTypeValues.map((element, index)=>
<Button variant="contained" disabled={index !== -1 && index !== selectedButtonIndex} onClick={() => setSelectedButtonIndex(index)} color="primary">{element.name</Button>
)}
Note: I started with -1
as initial value, as this enables all buttons initially and then it locks your choice. You could use another state to signal the fact that a choice has been made.