Let's see an example on how to disable a button using a function in React:
jsximport React from 'react'; const SpecialButton = () => { const greeting = () => { console.log('Hi'); } const isMonday = () => { let now = new Date(); return now.getDay() === 1 ? true : false; } return( <button onClick = {greeting} disabled = {isMonday()}>Click me if it's not Monday</button> ); } export default SpecialButton;
Notice the difference between onClick
and disabled
props. On the former, you should pass a reference to a function that will run on click. On the latter, you should run the function on render; that's why you write the function using parenthesis isMonday()
.
Let's see another example:
jsximport React from 'react'; const SpecialButton = () => { const greeting = () => { console.log('Hi'); } const isDivisibleBySeven = (num) => { return num % 7 === 0 ? true : false; } return( <button onClick = {greeting} disabled = {isDivisibleBySeven(84)}>Click me if the number is not divisible by 7</button> ); } export default SpecialButton;
In this case, you pass a number as a parameter and you are disabling the button if the number is divisible by 7.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.