Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting conditional onClick behaviour in React Component

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?

like image 975
GroomedGorilla Avatar asked Jun 19 '17 10:06

GroomedGorilla


People also ask

How do you add condition to onClick in React?

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.

Can you add onClick to React component?

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.

How do I change the onClick component in React?

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.

How do you trigger onClick event in react JS?

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.


1 Answers

This should work:

onClick={() => { props.inputText === '' ? 
   alert("Text cannot be blank.") : 
   props.onSubmit(props.inputText)  }}
like image 76
CD.. Avatar answered Sep 21 '22 23:09

CD..