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?
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>
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>
);
}
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.
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.