loading
is being set and passed into props, but when onClick
is pressed on any button, the loader is loading on all instances of item
trigger on. How can I make the loader run only on pressed buttons?
List.map((item, i) => { return( <Button onClick={(e) => !props.loading && e.stopPropagation()}> Save {props.loading && (<CircularProgress/>)} </Button> ); });
P粉1916105802024-03-31 12:47:11
You must use an array of Ids to render the loading in each button instead of loading a boolean variable in the parent component. Here is an example: You can check this code in the code sandbox here.
import "./styles.css"; import CircularProgress from "@mui/material/CircularProgress"; import { useState } from "react"; const items = ["1", "2", "3", "4", "5", "6"]; export default function App() { const [loading, setLoading] = useState([]); return ({items.map((item) => ( ))}); }
This is a simple example of what I implemented. If the user clicks a button, only that button will render the loading spinner. You can achieve this in many ways. You can also add logic to remove the load if the user clicks the load button by checking if the item exists in the state. If it is, you can simply remove it from the load list.