Setting conditional onClick behavior in React component
I am working on a component where a button (input field of type "submit") will submit data upon click. However, I would like to introduce a guarantee to show a warning on the screen if the input field is empty.
Thinking this would work in the same way as for component attributes, I tried the options effortlessly:
onClick={props.inputText === ''
?
alert("Text cannot be blank.")
:
(e => props.onSubmit(props.inputText))}/>
I'd rather not run validation inside the onSubmit function to isolate store updates as much as possible (I'm following the React-Redux framework).
Any idea if and how JSX handles such a situation?
+3
source to share
2 answers
You are assigning a value onClick event
, but the onclick expects a function. To do this, complete all logic inside the 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);
}
+1
source to share