Function undefined inside a component - reactjs

im trying reactjs and i got an undefined and i dont kow why.
The code is really simple but maybe i didnt get something ?!
isMailValid(mail) {
const valid_mail = RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
console.log("res => " + valid_mail.test(mail));
return valid_mail.test(mail);
}
isMailOk() {
var res = this.isMailValid(this.state.mail)
if (res === true)
return (<p class="false">invalid mail</p>);
return (<p class="good">Mail Ok</p>);
}
I got 'isMailValid' is not defined no-undef.
Thx for help

The function is undefined because it is not in the same scope as the function calling it. To access it you'll have to prefix the call with this. to tell React where to find the function.
isMailOk() {
if (this.isMailValid(this.state.mail) === true)
return (<p class="false">Mail invalid</p>);
return (<p class="good">Mail Ok</p>);
}
You'll also have to bind your custom function to this. You can do that by placing this.isMailOk = this.isMailOk.bind(this); in the constructor. You'll have to do that with both of your custom functions. Functions such as render don't require being bound to this because they are inherited when you extend your class from React.Component. You can read more about binding to this in the docs.

Related

How to extract "=>" to function model

I am fresher here, trying to start using => for functions and can't quite understand the inner part of a function in this code. It does work, wrote it myself, but just want to fully understand how and why.
Is there any other form you could write the exact same code in different "shape"?
I understand how first function extracts to:
function deleteNote(NoteID) {
...
}
But can't figure out how does the inner part work.
const deleteNote = noteID => {
setNote(existingNotes => { return existingNotes.filter((note) => note.id !== noteID);
})
}
Result is fine, just want to clarify what's going on... :)
In short, that could all be translated to:
const deleteNote = function(noteId) {
setNote(function(existingNotes) {
return existingNotes.filter(function(note) {
return note.id !== noteID;
});
});
};
If you wrap the part after => in curly brackets {}, then you need a return statement to return something, such as in:
setNote(existingNotes => {
return ...;
})
If you don't wrap it around curly brackets, then whatever you put after the arrow is what will be returned, such as in:
existingNotes.filter((note) => note.id !== noteID);
Take a look at this short article.
To add to Elder's answer, another easier way of getting used to arrow function is by dissecting the calls into separate named functions (which is what we are commonly used to).
So for example:
existingNotes.filter((note) => note.id !== noteID);
Could also be viewed as:
function noteDifferent(note) {
return (note.id !== noteID);
}
existingNotes.filter(noteDifferent);
Array.filter(fn) expects a callback function 'fn' as a parameter, and will send the element note in this case, to said function.

how to pass jsx as a string inside the return call

Is it possible to do something like:
const data={
star: "<h1>STAR</h1>",
moon: "<h3>moon</h3>"
}
const App = () => {
return(
<div>{data.start}</div>
);
}
what i get is the actual string of <h1>STAR</h1> not just STAR
I don't think you can. You can return an html string and possibly get it to display, but JSX isn't a string, it gets compiled into javscript code that creates those elements. it works when your app is built, I don't think you can use dynamic strings with it at run-time. You could do something like this:
const getData = (which) => {
if (which === 'star') {
return (<h1>STAR</h1>);
}
if (which === 'moon') {
return (<h3>moon</h3>);
}
return null; // nothing will display
}
const App = () => {
return (
<div>{getData('star')}</div>
);
};
Strings can be converted to JSX with third-party libraries such as h2x or react-render-html. It may be unsafe to do this with user input because of possible vulnerabilities and security problems that may exist libraries that parse DOM.
It's impossible to use components this way because component names aren't associated with functions that implement them during conversion.

What does "SomeName => {}" mean?

I'm new to react coming from a .Net background and I was trying to create a class, I tried numerous ways of doing so but in this instance I was unable to create a constructor in this variation and came to the conclusion that this maybe isn't a class, I've searched around the web but haven't found any info
Here is an example:
export default ViewTestStuff => {
constructor(){
// errors
}
return (
<div>
<p>Hello</p>
</div>
)
}
so my question is what is the "=> {}" in this example, is this a class? and why can't I create a constructor in it if it is indeed a class
It is a Arrow Function from es6, and has nothing to do with React.js
const add = (a, b) => a+b;
it is just a function.
calling add(2, 3) returns 5
One important thing to remember is, that arrow functions do not have the prototype chain. You also cannot call them with new.
Another thing to notice is, that this is bound to the context where the arrow function is defined.
const obj = {
name: "Lukas",
method: function() {
var self = this;
console.log(this.name === "Lukas");
return [
function() {
console.log(this !== self)
},
() => {
console.log(this === self)
}
];
}
}
const [func, arrow] = obj.method();
func();
arrow();
see the docs
It is an arrow function! A nice feature on ES6, that is already implemented on most modern browsers.
Something => {} Means a function with Something as it's parameter and an empty body. It is similar to:
function (Something) {
}
In your case, it's the same as:
export default function (ViewTestStuff) {
constructor(){
// errors
}
return (
<div>
<p>Hello</p>
</div>
)
}
And it's indeed invalid.
This is not a React thing... arrow functions are new in es6 javascript. More info can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Why function works without "this" binding?

I'm using React and Redux. I have a question. I know when I need "this" in a function I should bind it. But without binding my code works. Why ?
Function :
onSubmit() {
this.props.dispatch({type: 'ADD_TO_LIST', payload: this.state.inputValue});
}
And this is my render input :
<input type="text" placeholder="Enter Your Text ..." onChange={(e) => {
this.setState({inputValue: e.target.value})}} onKeyDown={(e) => {
if (e.key === 'Enter') {
this.onSubmit()
}
}}/>
You have idea about "when binding is required", but you missed one thing, "calling function will have the this (object by which it was called)". The value of this is determined by how a function is called.
Here:
this.onSubmit()
You are calling submit with this (class instance), so this (inside submit) will refer to class instance.
Check these references:
MDN Doc
Why is JavaScript bind() necessary?
Because you used an arrow function to call it, it's not the event handler itself. The arrow function is already bound correctly.
While function is binding (it changes this), ES6 arrow functions are non-binding. An example:
this.a = 1;
obj = {
a: 2,
bfunction: function() { return this.a; },
barrow: () => { return this.a; },
}
console.log(obj.bfunction()) // 2
console.log(obj.barrow()) // 1

How to declare a callback function using a contextual object as "this" in TypeScript?

What should be the right way to declare a function in order to filter an array of objects?
It could be a method in a class, but it becomes messy when parameters need to be added.
this.works = this.base_works.filter(whatever,{some : value});
whatever(x){
return x.value !== this.some;
}
Im not sure that declaring the function on the same general class is clean.
Any thoughts?
Thanks!
Ok I tried the two options, arrow function
var myFunction = (x) => {
return x.category !== undefined && x.category.indexOf(this.current_filter) !== -1;
}
And
normal
var myFunction = function (x) {
return x.category !== undefined && x.category.indexOf(this.current_filter) !== -1;
}
When I called the the first one, the reference this is to the object. On the latter the reference on this, is just him and his arguments.
The second one is the one that is perfect to use on the array callbacks. Thanks suraj to help me to find the solution!

Resources