17

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?

GroomedGorilla
  • 920
  • 2
  • 10
  • 30

2 Answers2

33

This should work:

onClick={() => { props.inputText === '' ? 
   alert("Text cannot be blank.") : 
   props.onSubmit(props.inputText)  }}
CD..
  • 72,281
  • 25
  • 154
  • 163
6

You are assigning the value to onClick event, but onclick expect a function. To achieve that wrap all the logic inside a function body.

Write it like this:

onClick={ e => {
    props.inputText === '' ? 
        alert("Text cannot be blank.") 
    : 
        props.onSubmit(props.inputText)}
    }
/>

Or

onClick={this.onClick.bind(this)/>

onClick(e){
    if(props.inputText === ''){
        alert("Text cannot be blank.");
        return;
    }
    props.onSubmit(props.inputText);
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142