javascript use in React setState - javascript

I'm studying a React book but see a simple like this, but I don't know why there is a ',' behind the [item]:value]
handleChange(item ,e) {
const {value} = e.target;
this.setState({[item]:value,});
}
render() {
const {name, age} = this.state;
return (
<div className="FormA">
name: <input value={name} onChange={this.handleChange.bind(this,'name')}/>
age: <input value={age} onChange={this.handleChange.bind(this,'age')}/>
</div>
);
}

It is considered as best practice to have a ',' after every object property. You must have used ESLint: https://eslint.org/docs/rules/comma-style
It is just a matter of syntax and does not add anything to your code.

Its a best practice, because of the below reasons
Its easier to track the commas. Eg. If you want a long list of object properties and you want to comment out some of them, then you need not worry about comas, as they are commented as well. Same goes for copy-paste.
Its easier to see the diffs in version control.
The commas can be either at the end or at the front.
[I usually use at front, personal choice.]
To Quote from ESList rules
The Comma Style rule enforces styles for comma-separated lists. There are two comma styles primarily used in JavaScript:
The standard style, in which commas are placed at the end of the current line
Comma First style, in which commas are placed at the start of the next line
One of the justifications for using Comma First style is that it can help track missing and trailing commas. These are problematic because missing commas in variable declarations can lead to the leakage of global variables and trailing commas can lead to errors in older versions of IE.
Refer:
https://eslint.org/docs/rules/comma-dangle,
https://medium.com/#nikgraf/why-you-should-enforce-dangling-commas-for-multiline-statements-d034c98e36f8,
https://eslint.org/docs/rules/comma-style

This is because you can define a collection of named values to be set. If you're going to set only one you don't need to use it. In the same way the last element does't need it neither, for example:
this.setState({[item]:value}); //You don't necessary need the ',' here.
this.setState({
[item]:value, //here you need to use ','
[item2]:value2, //here you need to use ','
[item3]:value3}); //here you don't need to use ','
For more infor about objects check this link and this one

Related

How can I remove empty strings in template literals?

I'm creating a script that loops through an array of objects and creates .edn file that we're using to migrate some of our client's data.
As we have to use .edn file which uses Clojure, I generate a template literal string and populate the data in the format that we need.
In the generated string I have many conditional operations, where I check if some data exist before returning some string. If the data doesn't exist I cannot use null, so I use an empty string. Now when my file gets created, those empty strings create an extra line that I want to remove. Investigating it more, the string adds /n which actually creates those extra lines from an empty string.
What is the best way to do it?
This is an example of what I'm doing:
arrayOfObjects.map(a => {
return `
; ...other code that doesn't depend on data
; Code that depends on data, if it's false I want to remove it completely and
; and avoid passing empty string as it creates extra space in the generated file
${a.stripe_connected_account
? `[[:im.stripeAccount/id]
#:im.stripeAccount{:stripeAccountId "${a.stripe_connected_account}"
:user #im/ref :user/${a.user}}]`
: ""}
`;
});
Appreciate any help, thanks!
An empty string doesn't do that. T${''}h${''}i${''}s is no different from This. The "extra space" is the whitespace that you (unconditionally) include in your template string around the ${ } part:
If you'd start the ${ } expression earlier and end it later and put the whitespace (if you even want it) as part of your if-true expression of the ternary, you will get what you want.
For example:
arrayOfObjects.map(a => {
return `
; ...other code that doesn't depend on data
; Code that depends on data, if it's false I want to remove it completely and
; and avoid passing empty string as it creates extra space in the generated file${
a.stripe_connected_account ? `
[[:im.stripeAccount/id]
#:im.stripeAccount{:stripeAccountId "${a.stripe_connected_account}"
:user #im/ref :user/${a.user}}]`
: ""
}`;
});
(Yes, the strange indentation is a result of merging two different indentation levels, the code's and the output's, and preventing line breaks in the output unless desired. I tried several ways to format it but none of them looked good - there are only ugly ways, no way to indent it nicely and have the result you want, unless you were to write a tagged template function that would smartly detect when a ${ } expression would need surrounding whitespace stripped and when it wouldn't.)

Replacing string literal css class-name in js/react code with a declared constant?

Kinda new to the whole html/js/css/react world... So, let's say I have a react component that generates a div that I want to style, so I set
<div className={"my-class-name"}>
{// stuff here
}
</div>
Then in a .css file:
.my-class-name{
color : blue
}
Here "my-class-name" is a string literal, and string literals are bad-coding-101 in every language I've ever used, instead what to do is declare a constant once:
const MY_CLASS_NAME = "my-class-name"
and refer to the constant everywhere instead of the literal. For lots of reasons (you can change it in one place, you get compile-time not run-time errors, the IDE can know about it, etc.). But it doesn't seem like a css file can look up a javascript constant. Is there a way to do what I want? Am I thinking about this all wrong?
I tried googling, couldn't figure it out, any help is appreciated.

What is the default “tag” function for template literals?

What is the name of the native function that handles template literals?
That is, I know that when you write tag`Foo ${'bar'}.`;, that’s just syntactic sugar for tag(['Foo ', '.'], 'bar');.¹
But what about just ​`Foo ${'bar'}.`;? I can’t just “call” (['Foo ', '.'], 'bar');. If I already have arguments in that form, what function should I pass them to?
I am only interested in the native function that implements the template literal functionality. I am quite capable of rolling my own, but the purpose of this question is to avoid that and do it “properly”—even if my implementation is a perfect match of current native functionality, the native functionality can change and I want my usage to still match. So answers to this question should take on one of the following forms:
The name of the native function to use, ideally with links to and/or quotes from documentation of it.
Links to and/or quotes from the spec that defines precisely what the implementation of this function is, so that if I roll my own at least I can be sure it’s up to the (current) specifications.
A backed-up statement that the native implementation is unavailable and unspecified. Ideally this is backed up by, again, links to and/or quotes from documentation, but if that’s unavailable, I’ll accept other sources or argumentation that backs this claim up.
Actually, the first argument needs a raw property, since it’s a TemplateStringsArray rather than a regular array, but I’m skipping that here for the sake of making the example more readable.
Motivation
I am trying to create a tag function (tag, say) that, internally, performs the default template literal concatenation on the input. That is, I am taking the TemplateStringsArray and the remaining arguments, and turning them into a single string that has already had its templating sorted out. (This is for passing the result into another tag function, otherTag perhaps, where I want the second function to treat everything as a single string literal rather than a broken up template.)
For example, tag`Something ${'cooked'}.`; would be equivalent to otherTag`Something cooked.`;.
My current approach
The definition of tag would look something like this:
function tag(textParts, ...expressions) {
const cooked = // an array with a single string value
const raw = // an array with a single string value
return otherTag({ ...cooked, raw });
}
Defining the value of raw is fairly straightforward: I know that String.raw is the tag function I need to call here, so const raw = [String.raw(textParts.raw, ...expressions)];.
But I cannot find anywhere on the internet what function I would call for the cooked part of it. What I want is, if I have tag`Something ${'cooked'}.`;, I want const cooked = `Something ${cooked}.`; in my function. But I can’t find the name of whatever function accomplishes that.
The closest I’ve found was a claim that it could be implemented as
const cooked = [expressions.map((exp, i) => textParts[i] + exp).join('')];
This is wrong—textParts may be longer than expressions, since tag`Something ${'cooked'}.`; gets ['Something ', '.'] and ['cooked'] as its arguments.
Improving this expression to handle that isn’t a problem:
const cooked = [
textParts
.map((text, i) => (i > 0 ? expressions[i-1] : '') + text)
.join(''),
];
But that’s not the point—I don’t want to roll my own here and risk it being inconsistent with the native implementation, particularly if that changes.
The name of the native function to use, ideally with links to and/or quotes from documentation of it.
There isn't one. It is syntax, not a function.
Links to and/or quotes from the spec that defines precisely what the implementation of this function is, so that if I roll my own at least I can be sure it’s up to the (current) specifications.
Section 13.2.8 Template Literals of the specification explains how to process the syntax.

Select class name (number) using RegEx & Jquery

I have a element like this
<div class="th-class2 th-hhjjsd th-context-78474378437834873"></div>
(Note: I know class names should not be pure numbers)
I want to get the numerical number from this div.
id = 78474378437834873
Is there a way I can use regular expressions to do it. I am nearly there but it only returns the first 4 numbers.
I use a clickevent to target the div and try and get the class like this
var classString = $(this).prop("class").match(/([0-9]+)/)[1];;
console.log(classString)
result is 7847
I am just not understanding how to get the rest of the number.
Thanks
You shouldn't use integers for class names because using a class typically means you are going to use the element more the once and adding a dynamic number defeats the purpose of classes, also working with someone else code and they use integers it's very hard to understand their code. As far as your questions goes, you shouldn't really use regular expressions to get a value of a class you should either store the value as an id so your element would look like this,
HTML
<div id="78474378437834873" class="th-class2 th-hhjjsd"></div>
or you could use a data object which is how I would do it like so,
HTML
<div class="th-class2 th-hhjjsd" data-object='{"value":78474378437834873}'></div>
and then when you select your element with your click event to get the value of the element you clicked console log the elements data object like so
jQuery
$('.th-class2').click(function() {
console.log($(this).data('object').value);
});
You should not use number only class names, they must start with an Alpha character [a-Z]
You can find what are the allowed characters in this discussion: Which characters are valid in CSS class names/selectors?
(Please make sure to read also the comments).
As per a solution for you,
The easy solution would be to use data attributes as so:
<div data-id="1000"></div>
and then you could get your id as simple as:
$(this).on('click', function() { console.log($(this).data('id')); } );
Happy Coding.

Using a variable when traversing elements in JQuery

Very quick and hopefully simple question.
I am trying to select a hidden input by value with some predefined variable.
var id = $("#puid").val();
$('input[value=id]').closest('tr').css({'background-color':'red'});
I thought the above code would have worked, however its not processing id as a variable. What is the right notation to do this? (I have tested the code by replacing id with the actual number and the rest of the code works fine).
remove it from the quotes, so the variable is concatenated into the string. They way you have it, it's looking for the literal value "id", and has no way of knowing that you're talking about a variable.
$('input[value='+id+']')
edit: more info - you could put double quotes around the id part, inside the strings, as in Nick's answer, which would make it safe to use with non-numeric ids. I omitted them since your example doesn't need them, as you said your ids are numeric.
Concatenate the string selector with the variable, like this:
var id = $("#puid").val();
$('input[value="' + id + '"]').closest('tr').css({'background-color':'red'});
Currently, it's looking exactly for this: value="id", but you want your variable there.

Categories

Resources