'How to move attribute expresion inside function and hide remove attribute only? React
I have logic for adding attributes. If an array has less than 1 item add attribute disabled: true else nothing.
<button {...(array.length < 1 ? { disabled: true } : {})}> Submit </button>
And this works fine, but I need to move this code to some function useCallback() or whatever and move the logic to a function.
Solution 1:[1]
I would suggest something like this
export default function App() {
const [btnDisabled, setBtnDisabled] = useState(true);
const [myArray, setMyArray] = useState([]);
useEffect(() => {
setMyArray([]);
}, []);
useEffect(() => {
if (myArray.length >= 1) {
setBtnDisabled(false);
}
}, [myArray]);
return (
<div className="App">
<button disabled={btnDisabled}> Submit </button>
</div>
);
}
you can try it here (I guess it would depend also on how your array data get changed) here is the link to try it https://codesandbox.io/s/lucid-rhodes-i2kttc?file=/src/App.js:69-556
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hakima maarouf |
