Setting conditional onClick behaviour in React Component - react-redux

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?

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

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);
}

Related

Vue.js Change text color based on 3 conditions

I have a table with 3 possible values: Firenze, Roma and Milano.
These 3 values need to be associated to 3 different colours.
On page load, every value should render with its associated colour.
Inline conditional rendering can't be used as it only can hold 2 values.
I've tried using functions such as this one below
($missing_item is a v-for single prop got from $missing_items which is an external array prop)
function getColour($missing_item){
switch($missing_item.Deposito){
case $missing_item.Deposito == 'Firenze':
return 'text-violet-400';
case $missing_item.Deposito == 'Roma':
return 'text-orange-400';
case $missing_item.Deposito == 'Milano':
return 'text-green-400';
}
}
I'm calling the function like this: :class="changeColour()"
but I keep getting the same error:
"Uncaught (in promise) TypeError: Cannot read properties of undefined
(reading 'Deposito')"
.
My main issue at this point is how to access the renderd "$missing_item.Deposito" inside a function
EDIT:
As I understand you try to call your method from a v-for. In this case just add the parameter from the loop:
<div v-for="(missing_item,index) in missing_items" :key="`Item${index}`">
<div :class="changeColour(missing_item)">
I change color depending on which city I am.
</div>
</div>
ORIGINAL ANSWER
There is no need for an additional function, Vue can handle this inside the class binding (see docs).
In your example it could look like this:
<div :class="$missing_item.Deposito == 'Firenze' || $missing_item.Deposito == 'Milano' ? 'text-green-400' : 'text-orange-400'">
{{ $missing_item.Deposito }}
</div>
While this works, the "Vue way" would be to use it in combination with a computed property like this:
<div :class="depositoStyle">
{{ $missing_item.Deposito }}
</div>
computed: {
depositoStyle() {
return this.$missing_item.Deposito == 'Firenze' || this.$missing_item.Deposito == 'Milano' ? 'text-green-400' : 'text-orange-400';
}
}
If you'd rather use a switch case than the short form, you can insert your switch case function into the computed property and return the end result.

array.some is not a function in My Laravel Vue Js Project

I Practicing laravel & Vue js project. Here i have a wishlist button.
<button
:class="wishlists.some(wishlist => wishlist.product_id === productId) ? activeClass:deactiveClass"
v-html="wishlists.some(wishlist => wishlist.product_id === productId) ? activeText:deactiveText"
#click="wishlistStatus(productId)" >
</button>
This is working perfectly but this is throwing also 2 errors.
[Vue warn]: Error in render: "TypeError: _vm.wishlists.some is not a function
and
TypeError: _vm.wishlists.some is not a function.
Now How I fix this
To use the 'some' method, your 'wishlists' variable must be an array.
If at the time your component initializes, that variable is not yet an array, then your application is going to crash.
This usually happens when you initialize your variable, for example, to null and then make a call to the server to fetch the data.
data() {
whislists: null,
...
}
There are several ways to fix this:
The simplest is to initialize your variable as an array.
data() {
whislists: [],
...
}
Another way to solve it would be to wait for your variable to become an array and then render your button, You can achieve this using a v-if.
<button
v-if="wishlists && wishlists.length"
:class="wishlists.some(wishlist => wishlist.product_id === productId) ?
activeClass:deactiveClass"
v-html="wishlists.some(wishlist => wishlist.product_id === productId) ?
activeText:deactiveText"
#click="wishlistStatus(productId)" >
</button>
This may be just one of the reasons why your problem occurs.
Other reasons could be:
You are assigning to your variable 'wishlists' data that is not an array without realizing it.

redux-form only show validation errors on submit

Is there a way to configure redux-form so that validation errors only show when the form is submitted?
Also I would like to clear an individual form field error when a user starts typing or makes a change.
Is this possible with redux-form?
You're responsible for rendering any validation errors, so you can configure them only to be visible after submission has failed (i.e. the user pressed submit and your validations came back as failing). For this, your input components wrapped with Field are passed a meta object as a prop that contains a submitFailed field that tells whether form submission has failed. The actual code for rendering that component could look something like this:
render() {
const { meta: { error, submitFailed } } = this.props
return (
// ... rendering the input and then some
{ error && submitFailed ? (
<span className="validation-error">{ error }</span>
) : null }
// ... rendering the rest
)
}
For not showing errors while the user is typing, you're responsible for enabling that behavior and the props passed to your wrapped input component hold the keys, this time the meta object holds a field called active, which tells you whether this input has focus or not. Code could be something like this (building on the previous example):
render() {
const { meta: { active, error, submitFailed } } = this.props
return (
// ... rendering the input and then some
{ !active && (error && submitFailed) ? (
<span className="validation-error">{ error }</span>
) : null }
// ... rendering the rest
)
}
Hope this helps!
I'm also had this problem, the reason was using touchOnChange flag
reduxForm({
form: 'MyForm',
enableReinitialize: true,
touchOnChange: true,
})
So I removed this flag from reduxForm options and the code started working correctly - I saw the validation errors on submit only
reduxForm({
form: 'MyForm',
enableReinitialize: true,
})
Example from official site
https://redux-form.com/8.2.2/examples/fieldlevelvalidation/

Redux Form - Not able to type anything in input

Hi I have upgraded to redux-form version 6.0.0 recently. And I am facing an issue like I am not able to type anything in the text field.
P.S I am also using Reactintl. I am using compose to aggregate connect, reduxform and intl decorator
Here is my code
Pastebin
If I understand correctly, then starting with v6 you should provide extra onBlur and onChange methods for the input in order to update its state. For your stateless component renderInput it could be done like this:
const renderInput = (field) => {
const onBlur = () => {
field.input.onBlur(field.input.value);
};
const onChange = (inputValue) => {
field.input.onChange(inputValue ? inputValue : '')
};
return <input {...field.input} onBlur={onBlur} onChange={onChange}
[...other options omitted for readability] />
}

How to add a custom validation to Magento prototype

I want to make a simple url validator for some custom fields. I tried the default ones (adding the class validate-url or validate-clean-url to the input) - but these don't work quite as I would like them to, so I want to write some of my own javascript, but integrated with the prototype validation.
Does anyone have any ideas how I can do this?
I didn't find anything helpful in my searches, and I am not very Prototype-savy (worked mostly with jQuery).
You can create your own custom validation function using
<script type="text/javascript">
var theForm = new VarienForm('theForm', true);
Validation.add('validate-must-be-baz','You failed to enter baz!',function(the_field_value){
if(the_field_value == 'baz')
{
return true;
}
return false;
});
</script>
See http://magento-quickies.tumblr.com/post/6579512188/magento-custom-form-validation
or
if(Validation) {
Validation.addAllThese([
[
'validation-myown',
'Please insert proper word',
function(v,r){ return v.indexOf('valid')==-1?false:true }
],
[ ]
])
}
see http://blog.baobaz.com/en/blog/custom-javascript-form-validators
In /js/prototype/validation.js (or the files for this kind of thing you have). You have a section with an array of :
classname :message on fail : function(v){your check return true/false;} to check if v is valid or not
This section is around line 420.
You can add your validation to this array or modify validate-url here is what it looks like :
['validate-url', 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)', function (v) {
v = (v || '').replace(/^\s+/, '').replace(/\s+$/, '');
return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))(\.[A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))*)(:(\d+))?(\/[A-Z0-9~](([A-Z0-9_~-]|\.)*[A-Z0-9~]|))*\/?(.*)?$/i.test(v)
}],
Edit : R.S answered maybe better by showing how to do without changing the js file. More convenient ;)

Resources