I'm working on a component where a button (input field of type 'submit') will submitting data once clicked. However, I'd like to introduce a safeguard to show an alert on screen if the input field is blank.
Thinking this would work the same way as it would for component attributes, I've tried variations on the following without much luck:
onClick={props.inputText === ''
?
alert("Text cannot be blank.")
:
(e => props.onSubmit(props.inputText))}/>
I'd rather not run the check inside the onSubmit function in order to isolate updates to the store as far as possible (I'm following a React-Redux structure).
Any idea if and how JSX handles a situation like this?
Use the ternary operator to conditionally add an onClick event handler in React, e.g. onClick={shouldAddEventHandler ? handleClick : undefined} . The ternary operator returns the value to the left of the colon if the condition is truthy.
The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.
To update a component's state on click, add an onClick prop to an element and set it to a function. The function will be invoked every time the element is clicked, which allows us to update the component's state on click.
To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.
This should work:
onClick={() => { props.inputText === '' ?
alert("Text cannot be blank.") :
props.onSubmit(props.inputText) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With