Back to articles
Let's DRY button "disabled"

Let's DRY button "disabled"

via Dev.to ReactDominik Dosoudil

I got this idea while fixing a bug where a button wasn’t disabled when it was supposed to be. I usually add a condition inside the click handler to make sure it doesn’t run (even though disabled should prevent that—just to be safe). Sometimes this is even necessary to avoid type errors. What bothers me is that the condition for the handler’s early return and the condition for disabling the button are usually the same. Not only is that annoying, but it’s also exactly where bugs tend to happen: something gets added to the condition in one place but not the other. That’s where the developer experience really suffers. const Example = () => { const [ value , setValue ] = useState ( '' ); const handleSubmit = () => { if ( value === '' ) { return ; // early return, value empty } // do something with the value }; return ( < div > < input value = { value } onChange = { ( e ) => setValue ( e . target . value ) } /> < button type = "submit" disabled = { value === '' } onClick = { handleSubmit } >

Continue reading on Dev.to React

Opens in a new tab

Read Full Article
6 views

Related Articles